-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
BrowserTabView.xaml.cs
374 lines (318 loc) · 15.4 KB
/
BrowserTabView.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright © 2013 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CefSharp.Example;
using CefSharp.Example.Handlers;
using CefSharp.Example.JavascriptBinding;
using CefSharp.Example.ModelBinding;
using CefSharp.Example.PostMessage;
using CefSharp.Fluent;
using CefSharp.Wpf.Example.Handlers;
using CefSharp.Wpf.Example.ViewModels;
using CefSharp.Wpf.Experimental;
using CefSharp.Wpf.Experimental.Accessibility;
namespace CefSharp.Wpf.Example.Views
{
public partial class BrowserTabView : UserControl
{
//Store draggable region if we have one - used for hit testing
private Region region;
public BrowserTabView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
browser.UsePopupMouseTransform();
//browser.BrowserSettings.BackgroundColor = Cef.ColorSetARGB(0, 255, 255, 255);
//Please remove the comments below to use the Experimental WpfImeKeyboardHandler.
//browser.WpfKeyboardHandler = new CefSharp.Wpf.Experimental.WpfImeKeyboardHandler(browser);
//Please remove the comments below to specify the color of the CompositionUnderline.
//var transparent = Colors.Transparent;
//var black = Colors.Black;
//ImeHandler.ColorBKCOLOR = Cef.ColorSetARGB(transparent.A, transparent.R, transparent.G, transparent.B);
//ImeHandler.ColorUNDERLINE = Cef.ColorSetARGB(black.A, black.R, black.G, black.B);
browser.RequestHandler = new ExampleRequestHandler();
//Test Handler allow All Permission
browser.PermissionHandler = new ExamplePermissionHandler();
var bindingOptions = new BindingOptions()
{
Binder = BindingOptions.DefaultBinder.Binder,
MethodInterceptor = new MethodInterceptorLogger(), // intercept .net methods calls from js and log it
#if !NETCOREAPP
PropertyInterceptor = new PropertyInterceptorLogger()
#endif
};
//To use the ResolveObject below and bind an object with isAsync:false we must set CefSharpSettings.WcfEnabled = true before
//the browser is initialized.
#if !NETCOREAPP
CefSharpSettings.WcfEnabled = true;
#endif
//If you call CefSharp.BindObjectAsync in javascript and pass in the name of an object which is not yet
//bound, then ResolveObject will be called, you can then register it
browser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
{
var repo = e.ObjectRepository;
//When JavascriptObjectRepository.Settings.LegacyBindingEnabled = true
//This event will be raised with ObjectName == Legacy so you can bind your
//legacy objects
#if NETCOREAPP
if (e.ObjectName == "Legacy")
{
repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions);
}
else
{
if (e.ObjectName == "boundAsync")
{
repo.Register("boundAsync", new AsyncBoundObject(), options: bindingOptions);
}
else if (e.ObjectName == "boundAsync2")
{
repo.Register("boundAsync2", new AsyncBoundObject(), options: bindingOptions);
}
}
#else
if (e.ObjectName == "Legacy")
{
repo.Register("bound", new BoundObject(), isAsync: false, options: BindingOptions.DefaultBinder);
repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
else
{
if (e.ObjectName == "bound")
{
repo.Register("bound", new BoundObject(), isAsync: false, options: bindingOptions);
}
else if (e.ObjectName == "boundAsync")
{
repo.Register("boundAsync", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
else if (e.ObjectName == "boundAsync2")
{
repo.Register("boundAsync2", new AsyncBoundObject(), isAsync: true, options: bindingOptions);
}
}
#endif
};
browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) =>
{
var name = e.ObjectName;
Debug.WriteLine($"Object {e.ObjectName} was bound successfully.");
};
browser.DisplayHandler = new DisplayHandler();
// This LifeSpanHandler implementaion demos hosting a popup in a ChromiumWebBrowser
// instance, it's still considered Experimental. The ChromiumWebBrowser
// is shown in a new Window. This could just as easily be a Tab/ContentControl/etc
/*
browser.LifeSpanHandler = CefSharp.Wpf.Experimental.LifeSpanHandler
.Create()
.OnPopupCreated((ctrl, targetUrl, targetFrameName, windowInfo) =>
{
var windowX = (windowInfo.X == int.MinValue) ? double.NaN : windowInfo.X;
var windowY = (windowInfo.Y == int.MinValue) ? double.NaN : windowInfo.Y;
var windowWidth = (windowInfo.Width == int.MinValue) ? double.NaN : windowInfo.Width;
var windowHeight = (windowInfo.Height == int.MinValue) ? double.NaN : windowInfo.Height;
var popup = new System.Windows.Window
{
Left = windowX,
Top = windowY,
Width = windowWidth,
Height = windowHeight,
Content = ctrl,
Owner = Window.GetWindow(browser),
Title = targetFrameName
};
popup.Closed += (o, e) =>
{
var w = o as System.Windows.Window;
if (w != null && w.Content is IWebBrowser)
{
(w.Content as IWebBrowser)?.Dispose();
w.Content = null;
}
};
})
.OnPopupBrowserCreated((ctrl, browser) =>
{
ctrl.Dispatcher.Invoke(() =>
{
var owner = System.Windows.Window.GetWindow(ctrl);
if (owner != null && owner.Content == ctrl)
{
owner.Show();
}
});
})
.OnPopupDestroyed((ctrl, popupBrowser) =>
{
//If browser is disposed then we don't need to remove the tab
if (!ctrl.IsDisposed)
{
var owner = System.Windows.Window.GetWindow(ctrl);
if (owner != null && owner.Content == ctrl)
{
owner.Close();
}
}
}).Build();
*/
browser.MenuHandler = new MenuHandler(addDevtoolsMenuItems:true);
//Enable experimental Accessibility support
browser.AccessibilityHandler = new AccessibilityHandler(browser);
browser.IsBrowserInitializedChanged += (sender, args) =>
{
if ((bool)args.NewValue)
{
//Uncomment to enable support
//browser.GetBrowserHost().SetAccessibilityState(CefState.Enabled);
}
};
browser.DownloadHandler = DownloadHandler
.Create()
.CanDownload((chromiumWebBrowser, browser, url, requestMethod) =>
{
//All all downloads
return true;
})
.OnBeforeDownload((chromiumWebBrowser, browser, downloadItem, callback) =>
{
UpdateDownloadAction("OnBeforeDownload", downloadItem);
//Show Dialog prompting user to save
callback.Continue("", showDialog: true);
return true;
}).OnDownloadUpdated((chromiumWebBrowser, browser, downloadItem, callback) =>
{
UpdateDownloadAction("OnDownloadUpdated", downloadItem);
})
.Build();
browser.AudioHandler = new CefSharp.Handler.AudioHandler();
browser.JsDialogHandler = new Handlers.JsDialogHandler();
//Read an embedded bitmap into a memory stream then register it as a resource you can then load custom://cefsharp/images/beach.jpg
var beachImageStream = new MemoryStream();
CefSharp.Example.Properties.Resources.beach.Save(beachImageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
browser.RegisterResourceHandler(CefExample.BaseUrl + "/images/beach.jpg", beachImageStream, Cef.GetMimeType("jpg"));
var dragHandler = new DragHandler();
dragHandler.RegionsChanged += OnDragHandlerRegionsChanged;
browser.DragHandler = dragHandler;
//browser.ResourceHandlerFactory = new InMemorySchemeAndResourceHandlerFactory();
//You can specify a custom RequestContext to share settings amount groups of ChromiumWebBrowsers
//browser.RequestContext = new RequestContext(new RequestContextHandler());
//NOTE - This is very important for this example as the default page will not load otherwise
//browser.RequestContext.RegisterSchemeHandlerFactory(CefSharpSchemeHandlerFactory.SchemeName, null, new CefSharpSchemeHandlerFactory());
//browser.RequestContext.RegisterSchemeHandlerFactory("https", "cefsharp.example", new CefSharpSchemeHandlerFactory());
//You can start setting preferences on a RequestContext that you created straight away, still needs to be called on the CEF UI thread.
//Cef.UIThreadTaskFactory.StartNew(delegate
//{
// string errorMessage;
// //Use this to check that settings preferences are working in your code
// var success = browser.RequestContext.SetPreference("webkit.webprefs.minimum_font_size", 24, out errorMessage);
//});
browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();
browser.LoadError += (sender, args) =>
{
//Aborted is generally safe to ignore
//Actions like starting a download will trigger an Aborted error
//which doesn't require any user action.
if (args.ErrorCode == CefErrorCode.Aborted)
{
return;
}
//Don't display an error for external protocols that we allow the OS to
//handle in OnProtocolExecution().
if (args.ErrorCode == CefErrorCode.UnknownUrlScheme && args.Frame.Url.StartsWith("mailto"))
{
return;
}
// Display a load error message.
var errorHtml = string.Format("<html><body><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
args.FailedUrl, args.ErrorText, args.ErrorCode);
_ = args.Browser.SetMainFrameDocumentContentAsync(errorHtml);
//AddressChanged isn't called for failed Urls so we need to manually update the Url TextBox
Dispatcher.InvokeAsync(() =>
{
var viewModel = (BrowserTabViewModel)this.DataContext;
viewModel.AddressEditable = args.FailedUrl;
});
};
CefExample.RegisterTestResources(browser);
browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
//TODO: Ideally we'd be able to bind this directly without having to use codebehind
var viewModel = e.NewValue as BrowserTabViewModel;
if (viewModel != null)
{
browser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = viewModel.LegacyBindingEnabled;
}
}
private void OnBrowserJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
//Complext objects are initially expresses as IDicionary (in reality it's an ExpandoObject so you can use dynamic)
if (typeof(System.Dynamic.ExpandoObject).IsAssignableFrom(e.Message.GetType()))
{
//You can use dynamic to access properties
//dynamic msg = e.Message;
//Alternatively you can use the built in Model Binder to convert to a custom model
var msg = e.ConvertMessageTo<PostMessageExample>();
if (msg.Type == "Update")
{
var callback = msg.Callback;
var type = msg.Type;
var property = msg.Data.Property;
callback.ExecuteAsync(type);
}
}
else if (e.Message is int)
{
e.Frame.ExecuteJavaScriptAsync("PostMessageIntTestCallback(" + (int)e.Message + ")");
}
}
private void UpdateDownloadAction(string downloadAction, DownloadItem downloadItem)
{
this.Dispatcher.InvokeAsync(() =>
{
var viewModel = (BrowserTabViewModel)this.DataContext;
viewModel.LastDownloadAction = downloadAction;
viewModel.DownloadItem = downloadItem;
});
}
private void OnBrowserMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var point = e.GetPosition(browser);
if (region.IsVisible((float)point.X, (float)point.Y))
{
var window = Window.GetWindow(this);
window.DragMove();
e.Handled = true;
}
}
private void OnDragHandlerRegionsChanged(Region region)
{
if (region != null)
{
//Only wire up event handler once
if (this.region == null)
{
browser.PreviewMouseLeftButtonDown += OnBrowserMouseLeftButtonDown;
}
this.region = region;
}
}
private void OnTextBoxGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.SelectAll();
}
private void OnTextBoxGotMouseCapture(object sender, MouseEventArgs e)
{
var textBox = (TextBox)sender;
textBox.SelectAll();
}
}
}