-
Notifications
You must be signed in to change notification settings - Fork 15k
/
electron_api_web_contents.cc
3936 lines (3428 loc) · 137 KB
/
electron_api_web_contents.cc
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/security_style_explanation.h"
#include "content/public/browser/security_style_explanations.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/native_window.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_dialog_helper.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/mouse_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(ENABLE_OSR)
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#endif
#if !defined(OS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if defined(OS_LINUX)
#include "ui/views/linux_ui/linux_ui.h"
#endif
#if defined(OS_LINUX) || defined(OS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "components/printing/browser/print_manager_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h"
#include "shell/browser/printing/print_preview_message_handler.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if defined(OS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif
#if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#ifndef MAS_BUILD
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
std::string type;
if (ConvertFromV8(isolate, val, &type)) {
if (type == "default") {
*out = printing::mojom::MarginType::kDefaultMargins;
return true;
}
if (type == "none") {
*out = printing::mojom::MarginType::kNoMargins;
return true;
}
if (type == "printableArea") {
*out = printing::mojom::MarginType::kPrintableAreaMargins;
return true;
}
if (type == "custom") {
*out = printing::mojom::MarginType::kCustomMargins;
return true;
}
}
return false;
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
std::string mode;
if (ConvertFromV8(isolate, val, &mode)) {
if (mode == "simplex") {
*out = printing::mojom::DuplexMode::kSimplex;
return true;
}
if (mode == "longEdge") {
*out = printing::mojom::DuplexMode::kLongEdge;
return true;
}
if (mode == "shortEdge") {
*out = printing::mojom::DuplexMode::kShortEdge;
return true;
}
}
return false;
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
std::string save_type;
if (!ConvertFromV8(isolate, val, &save_type))
return false;
save_type = base::ToLowerASCII(save_type);
if (save_type == "htmlonly") {
*out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML;
} else if (save_type == "htmlcomplete") {
*out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML;
} else if (save_type == "mhtml") {
*out = content::SAVE_PAGE_TYPE_AS_MHTML;
} else {
return false;
}
return true;
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Type = electron::api::WebContents::Type;
std::string type;
if (!ConvertFromV8(isolate, val, &type))
return false;
if (type == "backgroundPage") {
*out = Type::kBackgroundPage;
} else if (type == "browserView") {
*out = Type::kBrowserView;
} else if (type == "webview") {
*out = Type::kWebView;
#if BUILDFLAG(ENABLE_OSR)
} else if (type == "offscreen") {
*out = Type::kOffScreen;
#endif
} else {
return false;
}
return true;
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron {
namespace api {
namespace {
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
// Called when CapturePage is done.
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if defined(OS_MAC)
base::TimeDelta interval;
if (ui::TextInsertionCaretBlinkPeriod(&interval))
return interval;
#elif defined(OS_LINUX)
if (auto* linux_ui = views::LinuxUI::instance())
return linux_ui->GetCursorBlinkInterval();
#elif defined(OS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE)
? base::TimeDelta()
: base::TimeDelta::FromMilliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if defined(OS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#elif defined(OS_WIN)
printing::ScopedPrinterHandle printer;
return printer.OpenPrinterWithName(base::as_wcstr(device_name));
#endif
return true;
}
std::u16string GetDefaultPrinterAsync() {
#if defined(OS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
base::ThreadRestrictions::ScopedAllowIO allow_io;
#endif
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
print_backend->GetDefaultPrinterName(printer_name);
// Some devices won't have a default printer, so we should
// also check for existing printers and pick the first
// one should it exist.
if (printer_name.empty()) {
printing::PrinterList printers;
print_backend->EnumeratePrinters(&printers);
if (!printers.empty())
printer_name = printers.front().printer_name;
}
return base::UTF8ToUTF16(printer_name);
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !defined(OS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif defined(OS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().GetOrigin();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
std::unique_ptr<base::DictionaryValue> CreateFileSystemValue(
const FileSystem& file_system) {
auto file_system_value = std::make_unique<base::DictionaryValue>();
file_system_value->SetString("type", file_system.type);
file_system_value->SetString("fileSystemName", file_system.file_system_name);
file_system_value->SetString("rootURL", file_system.root_url);
file_system_value->SetString("fileSystemPath", file_system.file_system_path);
return file_system_value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::DictionaryValue* file_system_paths_value =
pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
if (file_system_paths_value) {
base::DictionaryValue::Iterator it(*file_system_paths_value);
for (; !it.IsAtEnd(); it.Advance()) {
std::string type =
it.value().is_string() ? it.value().GetString() : std::string();
result[it.key()] = type;
}
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
auto file_system_paths = GetAddedFileSystemPaths(web_contents);
return file_system_paths.find(file_system_path) != file_system_paths.end();
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly(
GetBrowserContext()->GetUserAgent()),
false);
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this)),
devtools_file_system_indexer_(
base::MakeRefCounted<DevToolsFileSystemIndexer>()),
file_task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
#if BUILDFLAG(ENABLE_OSR)
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
#endif
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
#if BUILDFLAG(ENABLE_OSR)
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
#endif
web_contents = content::WebContents::Create(params);
#if BUILDFLAG(ENABLE_OSR)
}
} else if (IsOffScreen()) {
bool transparent = false;
options.Get("transparent", &transparent);
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
#endif
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
// TODO(zcbenz): Make InitWithWebContents take unique_ptr.
// At the time of writing we are going through a refactoring and I don't want
// to make other people's work harder.
InitWithWebContents(owned_web_contents.release(), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if defined(OS_LINUX) || defined(OS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly(
GetBrowserContext()->GetUserAgent()),
false);
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(web_contents, GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(content::WebContents* web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintPreviewMessageHandler::CreateForWebContents(web_contents);
PrintViewManagerElectron::CreateForWebContents(web_contents);
printing::CreateCompositeClientIfNeeded(web_contents,
browser_context->GetUserAgent());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents, std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents);
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
web_contents, browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
if (guest_delegate_)
guest_delegate_->WillDestroy();
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asyncronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest() ||
type_ == Type::kBrowserView) {
delete this;
} else {
base::PostTask(FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(
[](base::WeakPtr<WebContents> contents) {
if (contents)
delete contents.get();
},
GetWeakPtr()));
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;