11using System ;
2+ using System . Diagnostics ;
3+ using Newtonsoft . Json ;
24using SharpWebview . Content ;
35
46namespace SharpWebview
@@ -19,9 +21,16 @@ public class Webview : IDisposable
1921 /// Set to true, to activate a debug view,
2022 /// if the current webview implementation supports it.
2123 /// </param>
22- public Webview ( bool debug = false )
24+ /// <param name="interceptExternalLinks">
25+ /// Set to true, top open external links in system browser.
26+ /// </param>
27+ public Webview ( bool debug = false , bool interceptExternalLinks = false )
2328 {
2429 _nativeWebview = Bindings . webview_create ( debug ? 1 : 0 , IntPtr . Zero ) ;
30+ if ( interceptExternalLinks )
31+ {
32+ InterceptExternalLinks ( ) ;
33+ }
2534 }
2635
2736 /// <summary>
@@ -138,6 +147,51 @@ protected virtual void Dispose(bool disposing)
138147 }
139148 }
140149
150+ private void InterceptExternalLinks ( )
151+ {
152+ // Bind a native method as javascript
153+ // This method opens the url parameter in the system browser
154+ Bind ( "openExternalLink" , ( id , req ) =>
155+ {
156+ dynamic args = JsonConvert . DeserializeObject ( req ) ;
157+ ProcessStartInfo psi = new ProcessStartInfo
158+ {
159+ FileName = args [ 0 ] ,
160+ UseShellExecute = true
161+ } ;
162+ Process . Start ( psi ) ;
163+
164+ Return ( id , RPCResult . Success , "{}" ) ;
165+ } ) ;
166+
167+ // On Init of the webview we inject some javascript
168+ // This javascript intercepts all click events and checks,
169+ // if the intercepted click is an external link.
170+ // In case on an external link the registered native method is called.
171+ InitScript ( @"
172+ function interceptClickEvent(e) {
173+ var href;
174+ var target = e.target || e.srcElement;
175+ if (target.tagName === 'A') {
176+ href = target.getAttribute('href');
177+ if(href.startsWith('http')
178+ && !href.startsWith('http://localhost')
179+ && !href.startsWith('http://127.0.0.1')
180+ ) {
181+ openExternalLink(href);
182+ e.preventDefault();
183+ }
184+ }
185+ }
186+
187+ if (document.addEventListener) {
188+ document.addEventListener('click', interceptClickEvent);
189+ } else if (document.attachEvent) {
190+ document.attachEvent('onclick', interceptClickEvent);
191+ }
192+ " ) ;
193+ }
194+
141195 ~ Webview ( ) => Dispose ( false ) ;
142196 }
143197}
0 commit comments