1
1
using System ;
2
+ using System . Diagnostics ;
3
+ using Newtonsoft . Json ;
2
4
using SharpWebview . Content ;
3
5
4
6
namespace SharpWebview
@@ -19,9 +21,16 @@ public class Webview : IDisposable
19
21
/// Set to true, to activate a debug view,
20
22
/// if the current webview implementation supports it.
21
23
/// </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 )
23
28
{
24
29
_nativeWebview = Bindings . webview_create ( debug ? 1 : 0 , IntPtr . Zero ) ;
30
+ if ( interceptExternalLinks )
31
+ {
32
+ InterceptExternalLinks ( ) ;
33
+ }
25
34
}
26
35
27
36
/// <summary>
@@ -138,6 +147,51 @@ protected virtual void Dispose(bool disposing)
138
147
}
139
148
}
140
149
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
+
141
195
~ Webview ( ) => Dispose ( false ) ;
142
196
}
143
197
}
0 commit comments