status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
369
body
stringlengths
0
254k
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
4
188
file_content
stringlengths
0
5.12M
closed
electron/electron
https://github.com/electron/electron
31,018
[Bug]: ContextIsolation changes page behavior and breaks protonmail login
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version any 15.x.y-beta, including beta.7 ### What operating system are you using? Other Linux ### Operating System Version Fedora 34 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.1 ### Expected Behavior Logins of Protonmail inside webviews should work and decrypt messages after login or show a message that the password was incorrect, regardless of the webpreferences of the webview. ### Actual Behavior On Electron 14 it works as expected, you can login and it all works. The same is true for Electron 15, but ONLY if you have enabled contextIsolation. I can't do that for my project as I need to overwrite existing window properties, and since the contextBridge doesn't allow this I have contextIsolation disabled. This isn't a big issue, as I only run a specific set of preloads inside the webview, but for some odd reason the protonmail login gives this vague error of "invalid character", that I can ONLY reproduce with contextIsolation disabled using the 15 betas. It does not happen in Chromium, it does not happen when enabling contextIsolation and it did not happen in Electron 14 and earlier, where you could just sign in. ### Testcase Gist URL https://gist.github.com/Jelmerro/65c3cabe4ac91461f382f6b15361b7b5 ### Additional Information _No response_
https://github.com/electron/electron/issues/31018
https://github.com/electron/electron/pull/35415
7e8607fd7a3dac522fce600a3e5fd03bda64efff
22ff2b6b933a52f7cfa85556aa8aaea7544b9d3f
2021-09-18T20:17:33Z
c++
2022-08-25T06:55:07Z
patches/node/buffer_fix_atob_input_validation.patch
closed
electron/electron
https://github.com/electron/electron
31,018
[Bug]: ContextIsolation changes page behavior and breaks protonmail login
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version any 15.x.y-beta, including beta.7 ### What operating system are you using? Other Linux ### Operating System Version Fedora 34 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.1 ### Expected Behavior Logins of Protonmail inside webviews should work and decrypt messages after login or show a message that the password was incorrect, regardless of the webpreferences of the webview. ### Actual Behavior On Electron 14 it works as expected, you can login and it all works. The same is true for Electron 15, but ONLY if you have enabled contextIsolation. I can't do that for my project as I need to overwrite existing window properties, and since the contextBridge doesn't allow this I have contextIsolation disabled. This isn't a big issue, as I only run a specific set of preloads inside the webview, but for some odd reason the protonmail login gives this vague error of "invalid character", that I can ONLY reproduce with contextIsolation disabled using the 15 betas. It does not happen in Chromium, it does not happen when enabling contextIsolation and it did not happen in Electron 14 and earlier, where you could just sign in. ### Testcase Gist URL https://gist.github.com/Jelmerro/65c3cabe4ac91461f382f6b15361b7b5 ### Additional Information _No response_
https://github.com/electron/electron/issues/31018
https://github.com/electron/electron/pull/35415
7e8607fd7a3dac522fce600a3e5fd03bda64efff
22ff2b6b933a52f7cfa85556aa8aaea7544b9d3f
2021-09-18T20:17:33Z
c++
2022-08-25T06:55:07Z
patches/node/.patches
refactor_alter_child_process_fork_to_use_execute_script_with.patch feat_initialize_asar_support.patch expose_get_builtin_module_function.patch build_add_gn_build_files.patch fix_add_default_values_for_variables_in_common_gypi.patch fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch pass_all_globals_through_require.patch build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch refactor_allow_embedder_overriding_of_internal_fs_calls.patch chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch chore_add_context_to_context_aware_module_prevention.patch chore_read_nobrowserglobals_from_global_not_process.patch fix_handle_boringssl_and_openssl_incompatibilities.patch src_allow_embedders_to_provide_a_custom_pageallocator_to.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch repl_fix_crash_when_sharedarraybuffer_disabled.patch fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch chore_fix_-wimplicit-fallthrough.patch fix_crash_caused_by_gethostnamew_on_windows_7.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_serdes_test.patch darwin_remove_eprototype_error_workaround_3405.patch darwin_translate_eprototype_to_econnreset_3413.patch darwin_bump_minimum_supported_version_to_10_15_3406.patch fix_failing_node_js_test_on_outdated.patch be_compatible_with_cppgc.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch worker_thread_add_asar_support.patch process_monitor_for_exit_with_kqueue_on_bsds_3441.patch process_bsd_handle_kevent_note_exit_failure_3451.patch reland_macos_use_posix_spawn_instead_of_fork_3257.patch process_reset_the_signal_mask_if_the_fork_fails_3537.patch process_only_use_f_dupfd_cloexec_if_it_is_defined_3512.patch unix_simplify_uv_cloexec_fcntl_3492.patch unix_remove_uv_cloexec_ioctl_3515.patch process_simplify_uv_write_int_calls_3519.patch macos_don_t_use_thread-unsafe_strtok_3524.patch process_fix_hang_after_note_exit_3521.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch fix_preserve_proper_method_names_as-is_in_error_stack.patch macos_avoid_posix_spawnp_cwd_bug_3597.patch src_update_importmoduledynamically.patch fix_add_v8_enable_reverse_jsargs_defines_in_common_gypi.patch json_parse_errors_made_user-friendly.patch support_v8_sandboxed_pointers.patch build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch build_ensure_native_module_compilation_fails_if_not_using_a_new.patch fix_override_createjob_in_node_platform.patch
closed
electron/electron
https://github.com/electron/electron
31,018
[Bug]: ContextIsolation changes page behavior and breaks protonmail login
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version any 15.x.y-beta, including beta.7 ### What operating system are you using? Other Linux ### Operating System Version Fedora 34 ### What arch are you using? x64 ### Last Known Working Electron version 14.0.1 ### Expected Behavior Logins of Protonmail inside webviews should work and decrypt messages after login or show a message that the password was incorrect, regardless of the webpreferences of the webview. ### Actual Behavior On Electron 14 it works as expected, you can login and it all works. The same is true for Electron 15, but ONLY if you have enabled contextIsolation. I can't do that for my project as I need to overwrite existing window properties, and since the contextBridge doesn't allow this I have contextIsolation disabled. This isn't a big issue, as I only run a specific set of preloads inside the webview, but for some odd reason the protonmail login gives this vague error of "invalid character", that I can ONLY reproduce with contextIsolation disabled using the 15 betas. It does not happen in Chromium, it does not happen when enabling contextIsolation and it did not happen in Electron 14 and earlier, where you could just sign in. ### Testcase Gist URL https://gist.github.com/Jelmerro/65c3cabe4ac91461f382f6b15361b7b5 ### Additional Information _No response_
https://github.com/electron/electron/issues/31018
https://github.com/electron/electron/pull/35415
7e8607fd7a3dac522fce600a3e5fd03bda64efff
22ff2b6b933a52f7cfa85556aa8aaea7544b9d3f
2021-09-18T20:17:33Z
c++
2022-08-25T06:55:07Z
patches/node/buffer_fix_atob_input_validation.patch
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
patches/chromium/fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
patches/chromium/fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
35,389
[Bug]: using debugger's Emulation.setDeviceMetricsOverride and changing origins(?) crashes Electron 21
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 21.0.0-alpha.1 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.3 ### Expected Behavior When setDeviceMetricsOverride is active and a different URL is loaded, the application does not crash ### Actual Behavior Electron crashes with a SIGSEGV, in all current Electron 21 alpha versions (1 through 4) ### Testcase Gist URL https://gist.github.com/25c3fea282cc3a95af280ed1db54ab3d ### Additional Information Run the application with Electron 21 and Electron 20. Click one of the buttons below the webview to change the URL - On Electron 21, the app now crashes - On Electron 20, the new URL is loaded On Electron 21, when showing the electron site, you can navigate to a few other pages like docs, releases and apps. Going to Blog crashes the app. Blog is still the same origin so that's why the "(?)" is in the title. Comment out these lines to prevent Electron 21 from crashing: https://gist.github.com/Kilian/25c3fea282cc3a95af280ed1db54ab3d#file-renderer-js-L18-L21
https://github.com/electron/electron/issues/35389
https://github.com/electron/electron/pull/35466
f6bbad287a7b15a760a018b85a3bb667d384e3c0
4744674e933ebbd294878b60c93732500fd4217a
2022-08-19T17:56:47Z
c++
2022-08-29T12:53:24Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,442
[Bug]: Upgrading to 19.0.13 break webpack hot reloading
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] #35489 ### Electron Version 19.0.13 ### What operating system are you using? macOS ### Operating System Version Monterey ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 19.0.12 ### Expected Behavior After upgrading to `19.0.13` webpack dev server reloading breaks. <img width="486" alt="CleanShot 2022-08-24 at 23 45 20@2x" src="https://user-images.githubusercontent.com/1192452/186594068-a984939d-dce8-4534-8dd0-634472275e60.png"> ### Actual Behavior The render process does not crash ### Testcase Gist URL _No response_ ### Additional Information Not sure how to capture the crash log but happy to provide it with some instructions!.
https://github.com/electron/electron/issues/35442
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-25T06:46:37Z
c++
2022-08-29T13:45:48Z
patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Mon, 31 Jan 2022 20:56:58 +0900 Subject: feat: add UV_LOOP_INTERRUPT_ON_IO_CHANGE option to uv_loop_configure https://github.com/libuv/libuv/pull/3308 diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 0f5ddfb3ca21b7e5b38d0a4ce4b9e77387597199..ba815202fb157aa82859ec0518523cf6f2ec6ba1 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -73,7 +73,15 @@ API This option is necessary to use :c:func:`uv_metrics_idle_time`. + - UV_LOOP_INTERRUPT_ON_IO_CHANGE: Interrupt the loop whenever a new IO + event has been added or changed. + + This option is usually when implementing event loop integration, to make + the polling of backend fd interrupt to recognize the changes of IO events. + .. versionchanged:: 1.39.0 added the UV_METRICS_IDLE_TIME option. + .. versionchanged:: 1.43.0 added the UV_LOOP_INTERRUPT_ON_IO_CHANGE option. + .. c:function:: int uv_loop_close(uv_loop_t* loop) diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 606083c87de5790d7e66fc34aeaae9a58acb8ef4..824b0b77cf5f0a46dcb3855c44ac73faaba2055f 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -252,7 +252,8 @@ typedef struct uv_statfs_s uv_statfs_t; typedef enum { UV_LOOP_BLOCK_SIGNAL = 0, - UV_METRICS_IDLE_TIME + UV_METRICS_IDLE_TIME, + UV_LOOP_INTERRUPT_ON_IO_CHANGE } uv_loop_option; typedef enum { diff --git a/deps/uv/src/unix/async.c b/deps/uv/src/unix/async.c index e1805c323795e5b0c465d80100eebeb7bf838caa..dd4358c0cdaa97ba8fadf4d9755993803beddd18 100644 --- a/deps/uv/src/unix/async.c +++ b/deps/uv/src/unix/async.c @@ -38,7 +38,6 @@ #include <sys/eventfd.h> #endif -static void uv__async_send(uv_loop_t* loop); static int uv__async_start(uv_loop_t* loop); @@ -70,7 +69,7 @@ int uv_async_send(uv_async_t* handle) { return 0; /* Wake up the other thread's event loop. */ - uv__async_send(handle->loop); + uv__loop_interrupt(handle->loop); /* Tell the other thread we're done. */ if (cmpxchgi(&handle->pending, 1, 2) != 1) @@ -165,40 +164,6 @@ static void uv__async_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } -static void uv__async_send(uv_loop_t* loop) { - const void* buf; - ssize_t len; - int fd; - int r; - - buf = ""; - len = 1; - fd = loop->async_wfd; - -#if defined(__linux__) - if (fd == -1) { - static const uint64_t val = 1; - buf = &val; - len = sizeof(val); - fd = loop->async_io_watcher.fd; /* eventfd */ - } -#endif - - do - r = write(fd, buf, len); - while (r == -1 && errno == EINTR); - - if (r == len) - return; - - if (r == -1) - if (errno == EAGAIN || errno == EWOULDBLOCK) - return; - - abort(); -} - - static int uv__async_start(uv_loop_t* loop) { int pipefd[2]; int err; diff --git a/deps/uv/src/unix/core.c b/deps/uv/src/unix/core.c index 7cd3a2a954ff7d70e6ba7a6f7538648841bc54b2..f89b7158218be60ac10e61484a2d5e5e28a3182f 100644 --- a/deps/uv/src/unix/core.c +++ b/deps/uv/src/unix/core.c @@ -887,6 +887,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) { loop->watchers[w->fd] = w; loop->nfds++; } + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -918,6 +921,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } else if (QUEUE_EMPTY(&w->watcher_queue)) QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -934,6 +940,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) { void uv__io_feed(uv_loop_t* loop, uv__io_t* w) { if (QUEUE_EMPTY(&w->pending_queue)) QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } diff --git a/deps/uv/src/unix/loop.c b/deps/uv/src/unix/loop.c index a88e71c339351f2ebcdd6c3f933fc3b1122910ed..353143e5ebecae598425dc036f4458bb7c43bb0b 100644 --- a/deps/uv/src/unix/loop.c +++ b/deps/uv/src/unix/loop.c @@ -217,6 +217,11 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + if (option != UV_LOOP_BLOCK_SIGNAL) return UV_ENOSYS; @@ -226,3 +231,37 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { loop->flags |= UV_LOOP_BLOCK_SIGPROF; return 0; } + + +void uv__loop_interrupt(uv_loop_t* loop) { + const void* buf; + ssize_t len; + int fd; + int r; + + buf = ""; + len = 1; + fd = loop->async_wfd; + +#if defined(__linux__) + if (fd == -1) { + static const uint64_t val = 1; + buf = &val; + len = sizeof(val); + fd = loop->async_io_watcher.fd; /* eventfd */ + } +#endif + + do + r = write(fd, buf, len); + while (r == -1 && errno == EINTR); + + if (r == len) + return; + + if (r == -1) + if (errno == EAGAIN || errno == EWOULDBLOCK) + return; + + abort(); +} diff --git a/deps/uv/src/uv-common.h b/deps/uv/src/uv-common.h index 6001b0cf68d0b0268b578218b664a737f43c9521..5d2212571f4bcb648ab332f0c5650d0fdb37c03a 100644 --- a/deps/uv/src/uv-common.h +++ b/deps/uv/src/uv-common.h @@ -140,6 +140,8 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap); void uv__loop_close(uv_loop_t* loop); +void uv__loop_interrupt(uv_loop_t* loop); + int uv__read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb); @@ -268,6 +270,10 @@ void uv__threadpool_cleanup(void); if (((h)->flags & UV_HANDLE_ACTIVE) != 0) break; \ (h)->flags |= UV_HANDLE_ACTIVE; \ if (((h)->flags & UV_HANDLE_REF) != 0) uv__active_handle_add(h); \ + int loop_flags = uv__get_internal_fields((h)->loop)->flags; \ + if (loop_flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) { \ + uv__loop_interrupt((h)->loop); \ + } \ } \ while (0) diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index e53a0f8e28637a58ceec7852d1a79874fc1a9548..dd4065c1cc68763bfe258492e3119669311394dc 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -381,10 +381,20 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + return UV_ENOSYS; } +void uv__loop_interrupt(uv_loop_t* loop) { + PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL); +} + + int uv_backend_fd(const uv_loop_t* loop) { return -1; } diff --git a/deps/uv/test/test-embed.c b/deps/uv/test/test-embed.c index c6ddceb149d9c1d68b0dd17b6dac0d4c3c3e9dbc..f6572c5dc2b6ef39bd11889ad1f7873007a6437d 100644 --- a/deps/uv/test/test-embed.c +++ b/deps/uv/test/test-embed.c @@ -25,115 +25,179 @@ #include <stdlib.h> #include <errno.h> -#ifndef HAVE_KQUEUE -# if defined(__APPLE__) || \ - defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__FreeBSD_kernel__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) -# define HAVE_KQUEUE 1 -# endif -#endif - #ifndef HAVE_EPOLL # if defined(__linux__) # define HAVE_EPOLL 1 # endif #endif -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) +#if defined(HAVE_EPOLL) +# include <sys/epoll.h> +#endif -#if defined(HAVE_KQUEUE) +#if !defined(_WIN32) # include <sys/types.h> -# include <sys/event.h> # include <sys/time.h> #endif -#if defined(HAVE_EPOLL) -# include <sys/epoll.h> -#endif - +static uv_loop_t main_loop; +static uv_loop_t external_loop; static uv_thread_t embed_thread; static uv_sem_t embed_sem; -static uv_timer_t embed_timer; static uv_async_t embed_async; +static uv_async_t main_async; static volatile int embed_closed; -static int embed_timer_called; +static uv_timer_t main_timer; +static int main_timer_called; -static void embed_thread_runner(void* arg) { +#if defined(_WIN32) +static void embed_thread_poll_win(HANDLE iocp, int timeout) { + DWORD bytes; + ULONG_PTR key; + OVERLAPPED* overlapped; + + GetQueuedCompletionStatus(iocp, + &bytes, + &key, + &overlapped, + timeout >= 0 ? timeout : INFINITE); + + /* Give the event back so the loop can deal with it. */ + if (overlapped != NULL) + PostQueuedCompletionStatus(iocp, + bytes, + key, + overlapped); +} +#else +static void embed_thread_poll_unix(int fd, int timeout) { int r; - int fd; + do { +#if defined(HAVE_EPOLL) + struct epoll_event ev; + r = epoll_wait(fd, &ev, 1, timeout); +#else + struct timeval tv; + if (timeout >= 0) { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + } + fd_set readset; + FD_ZERO(&readset); + FD_SET(fd, &readset); + r = select(fd + 1, &readset, NULL, NULL, timeout >= 0 ? &tv : NULL); +#endif + } while (r == -1 && errno == EINTR); +} +#endif /* !_WIN32 */ + + +static void embed_thread_runner(void* arg) { int timeout; - while (!embed_closed) { - fd = uv_backend_fd(uv_default_loop()); - timeout = uv_backend_timeout(uv_default_loop()); - - do { -#if defined(HAVE_KQUEUE) - struct timespec ts; - ts.tv_sec = timeout / 1000; - ts.tv_nsec = (timeout % 1000) * 1000000; - r = kevent(fd, NULL, 0, NULL, 0, &ts); -#elif defined(HAVE_EPOLL) - { - struct epoll_event ev; - r = epoll_wait(fd, &ev, 1, timeout); - } + do { + timeout = uv_backend_timeout(&main_loop); + +#if defined(_WIN32) + embed_thread_poll_win(main_loop.iocp, timeout); +#else + embed_thread_poll_unix(uv_backend_fd(&main_loop), timeout); #endif - } while (r == -1 && errno == EINTR); + uv_async_send(&embed_async); + uv_sem_wait(&embed_sem); - } + } while (!embed_closed); } static void embed_cb(uv_async_t* async) { - uv_run(uv_default_loop(), UV_RUN_ONCE); + /* Run tasks in main loop */ + uv_run(&main_loop, UV_RUN_NOWAIT); + /* Tell embed thread to continue polling */ uv_sem_post(&embed_sem); } -static void embed_timer_cb(uv_timer_t* timer) { - embed_timer_called++; +static void main_timer_cb(uv_timer_t* timer) { + main_timer_called++; embed_closed = 1; uv_close((uv_handle_t*) &embed_async, NULL); + uv_close((uv_handle_t*) &main_async, NULL); } -#endif -TEST_IMPL(embed) { -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) - uv_loop_t external; - - ASSERT(0 == uv_loop_init(&external)); +static void init_loops(void) { + ASSERT_EQ(0, uv_loop_init(&main_loop)); + ASSERT_EQ(0, uv_loop_init(&external_loop)); - embed_timer_called = 0; + main_timer_called = 0; embed_closed = 0; - uv_async_init(&external, &embed_async, embed_cb); + uv_async_init(&external_loop, &embed_async, embed_cb); - /* Start timer in default loop */ - uv_timer_init(uv_default_loop(), &embed_timer); - uv_timer_start(&embed_timer, embed_timer_cb, 250, 0); + /* Create a dummy async for main loop otherwise backend timeout will + always be 0 */ + uv_async_init(&main_loop, &main_async, embed_cb); - /* Start worker that will interrupt external loop */ + /* Start worker that will poll main loop and interrupt external loop */ uv_sem_init(&embed_sem, 0); uv_thread_create(&embed_thread, embed_thread_runner, NULL); +} - /* But run external loop */ - uv_run(&external, UV_RUN_DEFAULT); + +static void run_loop(void) { + /* Run external loop */ + uv_run(&external_loop, UV_RUN_DEFAULT); uv_thread_join(&embed_thread); - uv_loop_close(&external); + uv_sem_destroy(&embed_sem); + uv_loop_close(&external_loop); + uv_loop_close(&main_loop); +} - ASSERT(embed_timer_called == 1); -#endif + +TEST_IMPL(embed) { + init_loops(); + + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); + + return 0; +} + + +static uv_timer_t external_timer; + + +static void external_timer_cb(uv_timer_t* timer) { + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); +} + + +TEST_IMPL(embed_with_external_timer) { + init_loops(); + + /* Interrupt embed polling when a handle is started */ + ASSERT_EQ(0, uv_loop_configure(&main_loop, UV_LOOP_INTERRUPT_ON_IO_CHANGE)); + + /* Start timer in external loop, whose callback will not interrupt the + polling in embed thread */ + uv_timer_init(&external_loop, &external_timer); + uv_timer_start(&external_timer, external_timer_cb, 100, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); return 0; } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index a43edf1a4a9b0932ec73b8edaca0f676ecf3ccfa..199402e31406cf8ba360d54769461bb5285011ee 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -263,6 +263,7 @@ TEST_DECLARE (process_priority) TEST_DECLARE (has_ref) TEST_DECLARE (active) TEST_DECLARE (embed) +TEST_DECLARE (embed_with_external_timer) TEST_DECLARE (async) TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) @@ -860,6 +861,7 @@ TASK_LIST_START TEST_ENTRY (active) TEST_ENTRY (embed) + TEST_ENTRY (embed_with_external_timer) TEST_ENTRY (async) TEST_ENTRY (async_null_cb)
closed
electron/electron
https://github.com/electron/electron
35,442
[Bug]: Upgrading to 19.0.13 break webpack hot reloading
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] #35489 ### Electron Version 19.0.13 ### What operating system are you using? macOS ### Operating System Version Monterey ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 19.0.12 ### Expected Behavior After upgrading to `19.0.13` webpack dev server reloading breaks. <img width="486" alt="CleanShot 2022-08-24 at 23 45 20@2x" src="https://user-images.githubusercontent.com/1192452/186594068-a984939d-dce8-4534-8dd0-634472275e60.png"> ### Actual Behavior The render process does not crash ### Testcase Gist URL _No response_ ### Additional Information Not sure how to capture the crash log but happy to provide it with some instructions!.
https://github.com/electron/electron/issues/35442
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-25T06:46:37Z
c++
2022-08-29T13:45:48Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); uv_loop_close(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,384
[Bug]: Mac crash on WebWorker destructor
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.2 ### Expected Behavior When destructing WebWorkers, it should not crash ### Actual Behavior When destructing a WebWorker that uses WebAssembly, it crashes the v8 context. ### Testcase Gist URL _No response_ ### Additional Information It seems linked to the recent change to the "stop_and_close_uv_loop" change, seen here: #35322 If I revert that single change, it does not crash. Attached is a minidump [minidump.zip](https://github.com/electron/electron/files/9382529/e9384a04-0947-4e26-b452-c85e84309bf9.zip)
https://github.com/electron/electron/issues/35384
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-19T13:30:36Z
c++
2022-08-29T13:45:48Z
patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Mon, 31 Jan 2022 20:56:58 +0900 Subject: feat: add UV_LOOP_INTERRUPT_ON_IO_CHANGE option to uv_loop_configure https://github.com/libuv/libuv/pull/3308 diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 0f5ddfb3ca21b7e5b38d0a4ce4b9e77387597199..ba815202fb157aa82859ec0518523cf6f2ec6ba1 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -73,7 +73,15 @@ API This option is necessary to use :c:func:`uv_metrics_idle_time`. + - UV_LOOP_INTERRUPT_ON_IO_CHANGE: Interrupt the loop whenever a new IO + event has been added or changed. + + This option is usually when implementing event loop integration, to make + the polling of backend fd interrupt to recognize the changes of IO events. + .. versionchanged:: 1.39.0 added the UV_METRICS_IDLE_TIME option. + .. versionchanged:: 1.43.0 added the UV_LOOP_INTERRUPT_ON_IO_CHANGE option. + .. c:function:: int uv_loop_close(uv_loop_t* loop) diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 606083c87de5790d7e66fc34aeaae9a58acb8ef4..824b0b77cf5f0a46dcb3855c44ac73faaba2055f 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -252,7 +252,8 @@ typedef struct uv_statfs_s uv_statfs_t; typedef enum { UV_LOOP_BLOCK_SIGNAL = 0, - UV_METRICS_IDLE_TIME + UV_METRICS_IDLE_TIME, + UV_LOOP_INTERRUPT_ON_IO_CHANGE } uv_loop_option; typedef enum { diff --git a/deps/uv/src/unix/async.c b/deps/uv/src/unix/async.c index e1805c323795e5b0c465d80100eebeb7bf838caa..dd4358c0cdaa97ba8fadf4d9755993803beddd18 100644 --- a/deps/uv/src/unix/async.c +++ b/deps/uv/src/unix/async.c @@ -38,7 +38,6 @@ #include <sys/eventfd.h> #endif -static void uv__async_send(uv_loop_t* loop); static int uv__async_start(uv_loop_t* loop); @@ -70,7 +69,7 @@ int uv_async_send(uv_async_t* handle) { return 0; /* Wake up the other thread's event loop. */ - uv__async_send(handle->loop); + uv__loop_interrupt(handle->loop); /* Tell the other thread we're done. */ if (cmpxchgi(&handle->pending, 1, 2) != 1) @@ -165,40 +164,6 @@ static void uv__async_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } -static void uv__async_send(uv_loop_t* loop) { - const void* buf; - ssize_t len; - int fd; - int r; - - buf = ""; - len = 1; - fd = loop->async_wfd; - -#if defined(__linux__) - if (fd == -1) { - static const uint64_t val = 1; - buf = &val; - len = sizeof(val); - fd = loop->async_io_watcher.fd; /* eventfd */ - } -#endif - - do - r = write(fd, buf, len); - while (r == -1 && errno == EINTR); - - if (r == len) - return; - - if (r == -1) - if (errno == EAGAIN || errno == EWOULDBLOCK) - return; - - abort(); -} - - static int uv__async_start(uv_loop_t* loop) { int pipefd[2]; int err; diff --git a/deps/uv/src/unix/core.c b/deps/uv/src/unix/core.c index 7cd3a2a954ff7d70e6ba7a6f7538648841bc54b2..f89b7158218be60ac10e61484a2d5e5e28a3182f 100644 --- a/deps/uv/src/unix/core.c +++ b/deps/uv/src/unix/core.c @@ -887,6 +887,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) { loop->watchers[w->fd] = w; loop->nfds++; } + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -918,6 +921,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } else if (QUEUE_EMPTY(&w->watcher_queue)) QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -934,6 +940,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) { void uv__io_feed(uv_loop_t* loop, uv__io_t* w) { if (QUEUE_EMPTY(&w->pending_queue)) QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } diff --git a/deps/uv/src/unix/loop.c b/deps/uv/src/unix/loop.c index a88e71c339351f2ebcdd6c3f933fc3b1122910ed..353143e5ebecae598425dc036f4458bb7c43bb0b 100644 --- a/deps/uv/src/unix/loop.c +++ b/deps/uv/src/unix/loop.c @@ -217,6 +217,11 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + if (option != UV_LOOP_BLOCK_SIGNAL) return UV_ENOSYS; @@ -226,3 +231,37 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { loop->flags |= UV_LOOP_BLOCK_SIGPROF; return 0; } + + +void uv__loop_interrupt(uv_loop_t* loop) { + const void* buf; + ssize_t len; + int fd; + int r; + + buf = ""; + len = 1; + fd = loop->async_wfd; + +#if defined(__linux__) + if (fd == -1) { + static const uint64_t val = 1; + buf = &val; + len = sizeof(val); + fd = loop->async_io_watcher.fd; /* eventfd */ + } +#endif + + do + r = write(fd, buf, len); + while (r == -1 && errno == EINTR); + + if (r == len) + return; + + if (r == -1) + if (errno == EAGAIN || errno == EWOULDBLOCK) + return; + + abort(); +} diff --git a/deps/uv/src/uv-common.h b/deps/uv/src/uv-common.h index 6001b0cf68d0b0268b578218b664a737f43c9521..5d2212571f4bcb648ab332f0c5650d0fdb37c03a 100644 --- a/deps/uv/src/uv-common.h +++ b/deps/uv/src/uv-common.h @@ -140,6 +140,8 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap); void uv__loop_close(uv_loop_t* loop); +void uv__loop_interrupt(uv_loop_t* loop); + int uv__read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb); @@ -268,6 +270,10 @@ void uv__threadpool_cleanup(void); if (((h)->flags & UV_HANDLE_ACTIVE) != 0) break; \ (h)->flags |= UV_HANDLE_ACTIVE; \ if (((h)->flags & UV_HANDLE_REF) != 0) uv__active_handle_add(h); \ + int loop_flags = uv__get_internal_fields((h)->loop)->flags; \ + if (loop_flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) { \ + uv__loop_interrupt((h)->loop); \ + } \ } \ while (0) diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index e53a0f8e28637a58ceec7852d1a79874fc1a9548..dd4065c1cc68763bfe258492e3119669311394dc 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -381,10 +381,20 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + return UV_ENOSYS; } +void uv__loop_interrupt(uv_loop_t* loop) { + PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL); +} + + int uv_backend_fd(const uv_loop_t* loop) { return -1; } diff --git a/deps/uv/test/test-embed.c b/deps/uv/test/test-embed.c index c6ddceb149d9c1d68b0dd17b6dac0d4c3c3e9dbc..f6572c5dc2b6ef39bd11889ad1f7873007a6437d 100644 --- a/deps/uv/test/test-embed.c +++ b/deps/uv/test/test-embed.c @@ -25,115 +25,179 @@ #include <stdlib.h> #include <errno.h> -#ifndef HAVE_KQUEUE -# if defined(__APPLE__) || \ - defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__FreeBSD_kernel__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) -# define HAVE_KQUEUE 1 -# endif -#endif - #ifndef HAVE_EPOLL # if defined(__linux__) # define HAVE_EPOLL 1 # endif #endif -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) +#if defined(HAVE_EPOLL) +# include <sys/epoll.h> +#endif -#if defined(HAVE_KQUEUE) +#if !defined(_WIN32) # include <sys/types.h> -# include <sys/event.h> # include <sys/time.h> #endif -#if defined(HAVE_EPOLL) -# include <sys/epoll.h> -#endif - +static uv_loop_t main_loop; +static uv_loop_t external_loop; static uv_thread_t embed_thread; static uv_sem_t embed_sem; -static uv_timer_t embed_timer; static uv_async_t embed_async; +static uv_async_t main_async; static volatile int embed_closed; -static int embed_timer_called; +static uv_timer_t main_timer; +static int main_timer_called; -static void embed_thread_runner(void* arg) { +#if defined(_WIN32) +static void embed_thread_poll_win(HANDLE iocp, int timeout) { + DWORD bytes; + ULONG_PTR key; + OVERLAPPED* overlapped; + + GetQueuedCompletionStatus(iocp, + &bytes, + &key, + &overlapped, + timeout >= 0 ? timeout : INFINITE); + + /* Give the event back so the loop can deal with it. */ + if (overlapped != NULL) + PostQueuedCompletionStatus(iocp, + bytes, + key, + overlapped); +} +#else +static void embed_thread_poll_unix(int fd, int timeout) { int r; - int fd; + do { +#if defined(HAVE_EPOLL) + struct epoll_event ev; + r = epoll_wait(fd, &ev, 1, timeout); +#else + struct timeval tv; + if (timeout >= 0) { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + } + fd_set readset; + FD_ZERO(&readset); + FD_SET(fd, &readset); + r = select(fd + 1, &readset, NULL, NULL, timeout >= 0 ? &tv : NULL); +#endif + } while (r == -1 && errno == EINTR); +} +#endif /* !_WIN32 */ + + +static void embed_thread_runner(void* arg) { int timeout; - while (!embed_closed) { - fd = uv_backend_fd(uv_default_loop()); - timeout = uv_backend_timeout(uv_default_loop()); - - do { -#if defined(HAVE_KQUEUE) - struct timespec ts; - ts.tv_sec = timeout / 1000; - ts.tv_nsec = (timeout % 1000) * 1000000; - r = kevent(fd, NULL, 0, NULL, 0, &ts); -#elif defined(HAVE_EPOLL) - { - struct epoll_event ev; - r = epoll_wait(fd, &ev, 1, timeout); - } + do { + timeout = uv_backend_timeout(&main_loop); + +#if defined(_WIN32) + embed_thread_poll_win(main_loop.iocp, timeout); +#else + embed_thread_poll_unix(uv_backend_fd(&main_loop), timeout); #endif - } while (r == -1 && errno == EINTR); + uv_async_send(&embed_async); + uv_sem_wait(&embed_sem); - } + } while (!embed_closed); } static void embed_cb(uv_async_t* async) { - uv_run(uv_default_loop(), UV_RUN_ONCE); + /* Run tasks in main loop */ + uv_run(&main_loop, UV_RUN_NOWAIT); + /* Tell embed thread to continue polling */ uv_sem_post(&embed_sem); } -static void embed_timer_cb(uv_timer_t* timer) { - embed_timer_called++; +static void main_timer_cb(uv_timer_t* timer) { + main_timer_called++; embed_closed = 1; uv_close((uv_handle_t*) &embed_async, NULL); + uv_close((uv_handle_t*) &main_async, NULL); } -#endif -TEST_IMPL(embed) { -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) - uv_loop_t external; - - ASSERT(0 == uv_loop_init(&external)); +static void init_loops(void) { + ASSERT_EQ(0, uv_loop_init(&main_loop)); + ASSERT_EQ(0, uv_loop_init(&external_loop)); - embed_timer_called = 0; + main_timer_called = 0; embed_closed = 0; - uv_async_init(&external, &embed_async, embed_cb); + uv_async_init(&external_loop, &embed_async, embed_cb); - /* Start timer in default loop */ - uv_timer_init(uv_default_loop(), &embed_timer); - uv_timer_start(&embed_timer, embed_timer_cb, 250, 0); + /* Create a dummy async for main loop otherwise backend timeout will + always be 0 */ + uv_async_init(&main_loop, &main_async, embed_cb); - /* Start worker that will interrupt external loop */ + /* Start worker that will poll main loop and interrupt external loop */ uv_sem_init(&embed_sem, 0); uv_thread_create(&embed_thread, embed_thread_runner, NULL); +} - /* But run external loop */ - uv_run(&external, UV_RUN_DEFAULT); + +static void run_loop(void) { + /* Run external loop */ + uv_run(&external_loop, UV_RUN_DEFAULT); uv_thread_join(&embed_thread); - uv_loop_close(&external); + uv_sem_destroy(&embed_sem); + uv_loop_close(&external_loop); + uv_loop_close(&main_loop); +} - ASSERT(embed_timer_called == 1); -#endif + +TEST_IMPL(embed) { + init_loops(); + + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); + + return 0; +} + + +static uv_timer_t external_timer; + + +static void external_timer_cb(uv_timer_t* timer) { + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); +} + + +TEST_IMPL(embed_with_external_timer) { + init_loops(); + + /* Interrupt embed polling when a handle is started */ + ASSERT_EQ(0, uv_loop_configure(&main_loop, UV_LOOP_INTERRUPT_ON_IO_CHANGE)); + + /* Start timer in external loop, whose callback will not interrupt the + polling in embed thread */ + uv_timer_init(&external_loop, &external_timer); + uv_timer_start(&external_timer, external_timer_cb, 100, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); return 0; } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index a43edf1a4a9b0932ec73b8edaca0f676ecf3ccfa..199402e31406cf8ba360d54769461bb5285011ee 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -263,6 +263,7 @@ TEST_DECLARE (process_priority) TEST_DECLARE (has_ref) TEST_DECLARE (active) TEST_DECLARE (embed) +TEST_DECLARE (embed_with_external_timer) TEST_DECLARE (async) TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) @@ -860,6 +861,7 @@ TASK_LIST_START TEST_ENTRY (active) TEST_ENTRY (embed) + TEST_ENTRY (embed_with_external_timer) TEST_ENTRY (async) TEST_ENTRY (async_null_cb)
closed
electron/electron
https://github.com/electron/electron
35,384
[Bug]: Mac crash on WebWorker destructor
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.2 ### Expected Behavior When destructing WebWorkers, it should not crash ### Actual Behavior When destructing a WebWorker that uses WebAssembly, it crashes the v8 context. ### Testcase Gist URL _No response_ ### Additional Information It seems linked to the recent change to the "stop_and_close_uv_loop" change, seen here: #35322 If I revert that single change, it does not crash. Attached is a minidump [minidump.zip](https://github.com/electron/electron/files/9382529/e9384a04-0947-4e26-b452-c85e84309bf9.zip)
https://github.com/electron/electron/issues/35384
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-19T13:30:36Z
c++
2022-08-29T13:45:48Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); uv_loop_close(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,442
[Bug]: Upgrading to 19.0.13 break webpack hot reloading
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] #35489 ### Electron Version 19.0.13 ### What operating system are you using? macOS ### Operating System Version Monterey ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 19.0.12 ### Expected Behavior After upgrading to `19.0.13` webpack dev server reloading breaks. <img width="486" alt="CleanShot 2022-08-24 at 23 45 20@2x" src="https://user-images.githubusercontent.com/1192452/186594068-a984939d-dce8-4534-8dd0-634472275e60.png"> ### Actual Behavior The render process does not crash ### Testcase Gist URL _No response_ ### Additional Information Not sure how to capture the crash log but happy to provide it with some instructions!.
https://github.com/electron/electron/issues/35442
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-25T06:46:37Z
c++
2022-08-29T13:45:48Z
patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Mon, 31 Jan 2022 20:56:58 +0900 Subject: feat: add UV_LOOP_INTERRUPT_ON_IO_CHANGE option to uv_loop_configure https://github.com/libuv/libuv/pull/3308 diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 0f5ddfb3ca21b7e5b38d0a4ce4b9e77387597199..ba815202fb157aa82859ec0518523cf6f2ec6ba1 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -73,7 +73,15 @@ API This option is necessary to use :c:func:`uv_metrics_idle_time`. + - UV_LOOP_INTERRUPT_ON_IO_CHANGE: Interrupt the loop whenever a new IO + event has been added or changed. + + This option is usually when implementing event loop integration, to make + the polling of backend fd interrupt to recognize the changes of IO events. + .. versionchanged:: 1.39.0 added the UV_METRICS_IDLE_TIME option. + .. versionchanged:: 1.43.0 added the UV_LOOP_INTERRUPT_ON_IO_CHANGE option. + .. c:function:: int uv_loop_close(uv_loop_t* loop) diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 606083c87de5790d7e66fc34aeaae9a58acb8ef4..824b0b77cf5f0a46dcb3855c44ac73faaba2055f 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -252,7 +252,8 @@ typedef struct uv_statfs_s uv_statfs_t; typedef enum { UV_LOOP_BLOCK_SIGNAL = 0, - UV_METRICS_IDLE_TIME + UV_METRICS_IDLE_TIME, + UV_LOOP_INTERRUPT_ON_IO_CHANGE } uv_loop_option; typedef enum { diff --git a/deps/uv/src/unix/async.c b/deps/uv/src/unix/async.c index e1805c323795e5b0c465d80100eebeb7bf838caa..dd4358c0cdaa97ba8fadf4d9755993803beddd18 100644 --- a/deps/uv/src/unix/async.c +++ b/deps/uv/src/unix/async.c @@ -38,7 +38,6 @@ #include <sys/eventfd.h> #endif -static void uv__async_send(uv_loop_t* loop); static int uv__async_start(uv_loop_t* loop); @@ -70,7 +69,7 @@ int uv_async_send(uv_async_t* handle) { return 0; /* Wake up the other thread's event loop. */ - uv__async_send(handle->loop); + uv__loop_interrupt(handle->loop); /* Tell the other thread we're done. */ if (cmpxchgi(&handle->pending, 1, 2) != 1) @@ -165,40 +164,6 @@ static void uv__async_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } -static void uv__async_send(uv_loop_t* loop) { - const void* buf; - ssize_t len; - int fd; - int r; - - buf = ""; - len = 1; - fd = loop->async_wfd; - -#if defined(__linux__) - if (fd == -1) { - static const uint64_t val = 1; - buf = &val; - len = sizeof(val); - fd = loop->async_io_watcher.fd; /* eventfd */ - } -#endif - - do - r = write(fd, buf, len); - while (r == -1 && errno == EINTR); - - if (r == len) - return; - - if (r == -1) - if (errno == EAGAIN || errno == EWOULDBLOCK) - return; - - abort(); -} - - static int uv__async_start(uv_loop_t* loop) { int pipefd[2]; int err; diff --git a/deps/uv/src/unix/core.c b/deps/uv/src/unix/core.c index 7cd3a2a954ff7d70e6ba7a6f7538648841bc54b2..f89b7158218be60ac10e61484a2d5e5e28a3182f 100644 --- a/deps/uv/src/unix/core.c +++ b/deps/uv/src/unix/core.c @@ -887,6 +887,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) { loop->watchers[w->fd] = w; loop->nfds++; } + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -918,6 +921,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } else if (QUEUE_EMPTY(&w->watcher_queue)) QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -934,6 +940,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) { void uv__io_feed(uv_loop_t* loop, uv__io_t* w) { if (QUEUE_EMPTY(&w->pending_queue)) QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } diff --git a/deps/uv/src/unix/loop.c b/deps/uv/src/unix/loop.c index a88e71c339351f2ebcdd6c3f933fc3b1122910ed..353143e5ebecae598425dc036f4458bb7c43bb0b 100644 --- a/deps/uv/src/unix/loop.c +++ b/deps/uv/src/unix/loop.c @@ -217,6 +217,11 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + if (option != UV_LOOP_BLOCK_SIGNAL) return UV_ENOSYS; @@ -226,3 +231,37 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { loop->flags |= UV_LOOP_BLOCK_SIGPROF; return 0; } + + +void uv__loop_interrupt(uv_loop_t* loop) { + const void* buf; + ssize_t len; + int fd; + int r; + + buf = ""; + len = 1; + fd = loop->async_wfd; + +#if defined(__linux__) + if (fd == -1) { + static const uint64_t val = 1; + buf = &val; + len = sizeof(val); + fd = loop->async_io_watcher.fd; /* eventfd */ + } +#endif + + do + r = write(fd, buf, len); + while (r == -1 && errno == EINTR); + + if (r == len) + return; + + if (r == -1) + if (errno == EAGAIN || errno == EWOULDBLOCK) + return; + + abort(); +} diff --git a/deps/uv/src/uv-common.h b/deps/uv/src/uv-common.h index 6001b0cf68d0b0268b578218b664a737f43c9521..5d2212571f4bcb648ab332f0c5650d0fdb37c03a 100644 --- a/deps/uv/src/uv-common.h +++ b/deps/uv/src/uv-common.h @@ -140,6 +140,8 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap); void uv__loop_close(uv_loop_t* loop); +void uv__loop_interrupt(uv_loop_t* loop); + int uv__read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb); @@ -268,6 +270,10 @@ void uv__threadpool_cleanup(void); if (((h)->flags & UV_HANDLE_ACTIVE) != 0) break; \ (h)->flags |= UV_HANDLE_ACTIVE; \ if (((h)->flags & UV_HANDLE_REF) != 0) uv__active_handle_add(h); \ + int loop_flags = uv__get_internal_fields((h)->loop)->flags; \ + if (loop_flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) { \ + uv__loop_interrupt((h)->loop); \ + } \ } \ while (0) diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index e53a0f8e28637a58ceec7852d1a79874fc1a9548..dd4065c1cc68763bfe258492e3119669311394dc 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -381,10 +381,20 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + return UV_ENOSYS; } +void uv__loop_interrupt(uv_loop_t* loop) { + PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL); +} + + int uv_backend_fd(const uv_loop_t* loop) { return -1; } diff --git a/deps/uv/test/test-embed.c b/deps/uv/test/test-embed.c index c6ddceb149d9c1d68b0dd17b6dac0d4c3c3e9dbc..f6572c5dc2b6ef39bd11889ad1f7873007a6437d 100644 --- a/deps/uv/test/test-embed.c +++ b/deps/uv/test/test-embed.c @@ -25,115 +25,179 @@ #include <stdlib.h> #include <errno.h> -#ifndef HAVE_KQUEUE -# if defined(__APPLE__) || \ - defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__FreeBSD_kernel__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) -# define HAVE_KQUEUE 1 -# endif -#endif - #ifndef HAVE_EPOLL # if defined(__linux__) # define HAVE_EPOLL 1 # endif #endif -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) +#if defined(HAVE_EPOLL) +# include <sys/epoll.h> +#endif -#if defined(HAVE_KQUEUE) +#if !defined(_WIN32) # include <sys/types.h> -# include <sys/event.h> # include <sys/time.h> #endif -#if defined(HAVE_EPOLL) -# include <sys/epoll.h> -#endif - +static uv_loop_t main_loop; +static uv_loop_t external_loop; static uv_thread_t embed_thread; static uv_sem_t embed_sem; -static uv_timer_t embed_timer; static uv_async_t embed_async; +static uv_async_t main_async; static volatile int embed_closed; -static int embed_timer_called; +static uv_timer_t main_timer; +static int main_timer_called; -static void embed_thread_runner(void* arg) { +#if defined(_WIN32) +static void embed_thread_poll_win(HANDLE iocp, int timeout) { + DWORD bytes; + ULONG_PTR key; + OVERLAPPED* overlapped; + + GetQueuedCompletionStatus(iocp, + &bytes, + &key, + &overlapped, + timeout >= 0 ? timeout : INFINITE); + + /* Give the event back so the loop can deal with it. */ + if (overlapped != NULL) + PostQueuedCompletionStatus(iocp, + bytes, + key, + overlapped); +} +#else +static void embed_thread_poll_unix(int fd, int timeout) { int r; - int fd; + do { +#if defined(HAVE_EPOLL) + struct epoll_event ev; + r = epoll_wait(fd, &ev, 1, timeout); +#else + struct timeval tv; + if (timeout >= 0) { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + } + fd_set readset; + FD_ZERO(&readset); + FD_SET(fd, &readset); + r = select(fd + 1, &readset, NULL, NULL, timeout >= 0 ? &tv : NULL); +#endif + } while (r == -1 && errno == EINTR); +} +#endif /* !_WIN32 */ + + +static void embed_thread_runner(void* arg) { int timeout; - while (!embed_closed) { - fd = uv_backend_fd(uv_default_loop()); - timeout = uv_backend_timeout(uv_default_loop()); - - do { -#if defined(HAVE_KQUEUE) - struct timespec ts; - ts.tv_sec = timeout / 1000; - ts.tv_nsec = (timeout % 1000) * 1000000; - r = kevent(fd, NULL, 0, NULL, 0, &ts); -#elif defined(HAVE_EPOLL) - { - struct epoll_event ev; - r = epoll_wait(fd, &ev, 1, timeout); - } + do { + timeout = uv_backend_timeout(&main_loop); + +#if defined(_WIN32) + embed_thread_poll_win(main_loop.iocp, timeout); +#else + embed_thread_poll_unix(uv_backend_fd(&main_loop), timeout); #endif - } while (r == -1 && errno == EINTR); + uv_async_send(&embed_async); + uv_sem_wait(&embed_sem); - } + } while (!embed_closed); } static void embed_cb(uv_async_t* async) { - uv_run(uv_default_loop(), UV_RUN_ONCE); + /* Run tasks in main loop */ + uv_run(&main_loop, UV_RUN_NOWAIT); + /* Tell embed thread to continue polling */ uv_sem_post(&embed_sem); } -static void embed_timer_cb(uv_timer_t* timer) { - embed_timer_called++; +static void main_timer_cb(uv_timer_t* timer) { + main_timer_called++; embed_closed = 1; uv_close((uv_handle_t*) &embed_async, NULL); + uv_close((uv_handle_t*) &main_async, NULL); } -#endif -TEST_IMPL(embed) { -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) - uv_loop_t external; - - ASSERT(0 == uv_loop_init(&external)); +static void init_loops(void) { + ASSERT_EQ(0, uv_loop_init(&main_loop)); + ASSERT_EQ(0, uv_loop_init(&external_loop)); - embed_timer_called = 0; + main_timer_called = 0; embed_closed = 0; - uv_async_init(&external, &embed_async, embed_cb); + uv_async_init(&external_loop, &embed_async, embed_cb); - /* Start timer in default loop */ - uv_timer_init(uv_default_loop(), &embed_timer); - uv_timer_start(&embed_timer, embed_timer_cb, 250, 0); + /* Create a dummy async for main loop otherwise backend timeout will + always be 0 */ + uv_async_init(&main_loop, &main_async, embed_cb); - /* Start worker that will interrupt external loop */ + /* Start worker that will poll main loop and interrupt external loop */ uv_sem_init(&embed_sem, 0); uv_thread_create(&embed_thread, embed_thread_runner, NULL); +} - /* But run external loop */ - uv_run(&external, UV_RUN_DEFAULT); + +static void run_loop(void) { + /* Run external loop */ + uv_run(&external_loop, UV_RUN_DEFAULT); uv_thread_join(&embed_thread); - uv_loop_close(&external); + uv_sem_destroy(&embed_sem); + uv_loop_close(&external_loop); + uv_loop_close(&main_loop); +} - ASSERT(embed_timer_called == 1); -#endif + +TEST_IMPL(embed) { + init_loops(); + + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); + + return 0; +} + + +static uv_timer_t external_timer; + + +static void external_timer_cb(uv_timer_t* timer) { + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); +} + + +TEST_IMPL(embed_with_external_timer) { + init_loops(); + + /* Interrupt embed polling when a handle is started */ + ASSERT_EQ(0, uv_loop_configure(&main_loop, UV_LOOP_INTERRUPT_ON_IO_CHANGE)); + + /* Start timer in external loop, whose callback will not interrupt the + polling in embed thread */ + uv_timer_init(&external_loop, &external_timer); + uv_timer_start(&external_timer, external_timer_cb, 100, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); return 0; } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index a43edf1a4a9b0932ec73b8edaca0f676ecf3ccfa..199402e31406cf8ba360d54769461bb5285011ee 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -263,6 +263,7 @@ TEST_DECLARE (process_priority) TEST_DECLARE (has_ref) TEST_DECLARE (active) TEST_DECLARE (embed) +TEST_DECLARE (embed_with_external_timer) TEST_DECLARE (async) TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) @@ -860,6 +861,7 @@ TASK_LIST_START TEST_ENTRY (active) TEST_ENTRY (embed) + TEST_ENTRY (embed_with_external_timer) TEST_ENTRY (async) TEST_ENTRY (async_null_cb)
closed
electron/electron
https://github.com/electron/electron
35,442
[Bug]: Upgrading to 19.0.13 break webpack hot reloading
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] #35489 ### Electron Version 19.0.13 ### What operating system are you using? macOS ### Operating System Version Monterey ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 19.0.12 ### Expected Behavior After upgrading to `19.0.13` webpack dev server reloading breaks. <img width="486" alt="CleanShot 2022-08-24 at 23 45 20@2x" src="https://user-images.githubusercontent.com/1192452/186594068-a984939d-dce8-4534-8dd0-634472275e60.png"> ### Actual Behavior The render process does not crash ### Testcase Gist URL _No response_ ### Additional Information Not sure how to capture the crash log but happy to provide it with some instructions!.
https://github.com/electron/electron/issues/35442
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-25T06:46:37Z
c++
2022-08-29T13:45:48Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); uv_loop_close(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,384
[Bug]: Mac crash on WebWorker destructor
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.2 ### Expected Behavior When destructing WebWorkers, it should not crash ### Actual Behavior When destructing a WebWorker that uses WebAssembly, it crashes the v8 context. ### Testcase Gist URL _No response_ ### Additional Information It seems linked to the recent change to the "stop_and_close_uv_loop" change, seen here: #35322 If I revert that single change, it does not crash. Attached is a minidump [minidump.zip](https://github.com/electron/electron/files/9382529/e9384a04-0947-4e26-b452-c85e84309bf9.zip)
https://github.com/electron/electron/issues/35384
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-19T13:30:36Z
c++
2022-08-29T13:45:48Z
patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Mon, 31 Jan 2022 20:56:58 +0900 Subject: feat: add UV_LOOP_INTERRUPT_ON_IO_CHANGE option to uv_loop_configure https://github.com/libuv/libuv/pull/3308 diff --git a/deps/uv/docs/src/loop.rst b/deps/uv/docs/src/loop.rst index 0f5ddfb3ca21b7e5b38d0a4ce4b9e77387597199..ba815202fb157aa82859ec0518523cf6f2ec6ba1 100644 --- a/deps/uv/docs/src/loop.rst +++ b/deps/uv/docs/src/loop.rst @@ -73,7 +73,15 @@ API This option is necessary to use :c:func:`uv_metrics_idle_time`. + - UV_LOOP_INTERRUPT_ON_IO_CHANGE: Interrupt the loop whenever a new IO + event has been added or changed. + + This option is usually when implementing event loop integration, to make + the polling of backend fd interrupt to recognize the changes of IO events. + .. versionchanged:: 1.39.0 added the UV_METRICS_IDLE_TIME option. + .. versionchanged:: 1.43.0 added the UV_LOOP_INTERRUPT_ON_IO_CHANGE option. + .. c:function:: int uv_loop_close(uv_loop_t* loop) diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h index 606083c87de5790d7e66fc34aeaae9a58acb8ef4..824b0b77cf5f0a46dcb3855c44ac73faaba2055f 100644 --- a/deps/uv/include/uv.h +++ b/deps/uv/include/uv.h @@ -252,7 +252,8 @@ typedef struct uv_statfs_s uv_statfs_t; typedef enum { UV_LOOP_BLOCK_SIGNAL = 0, - UV_METRICS_IDLE_TIME + UV_METRICS_IDLE_TIME, + UV_LOOP_INTERRUPT_ON_IO_CHANGE } uv_loop_option; typedef enum { diff --git a/deps/uv/src/unix/async.c b/deps/uv/src/unix/async.c index e1805c323795e5b0c465d80100eebeb7bf838caa..dd4358c0cdaa97ba8fadf4d9755993803beddd18 100644 --- a/deps/uv/src/unix/async.c +++ b/deps/uv/src/unix/async.c @@ -38,7 +38,6 @@ #include <sys/eventfd.h> #endif -static void uv__async_send(uv_loop_t* loop); static int uv__async_start(uv_loop_t* loop); @@ -70,7 +69,7 @@ int uv_async_send(uv_async_t* handle) { return 0; /* Wake up the other thread's event loop. */ - uv__async_send(handle->loop); + uv__loop_interrupt(handle->loop); /* Tell the other thread we're done. */ if (cmpxchgi(&handle->pending, 1, 2) != 1) @@ -165,40 +164,6 @@ static void uv__async_io(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } -static void uv__async_send(uv_loop_t* loop) { - const void* buf; - ssize_t len; - int fd; - int r; - - buf = ""; - len = 1; - fd = loop->async_wfd; - -#if defined(__linux__) - if (fd == -1) { - static const uint64_t val = 1; - buf = &val; - len = sizeof(val); - fd = loop->async_io_watcher.fd; /* eventfd */ - } -#endif - - do - r = write(fd, buf, len); - while (r == -1 && errno == EINTR); - - if (r == len) - return; - - if (r == -1) - if (errno == EAGAIN || errno == EWOULDBLOCK) - return; - - abort(); -} - - static int uv__async_start(uv_loop_t* loop) { int pipefd[2]; int err; diff --git a/deps/uv/src/unix/core.c b/deps/uv/src/unix/core.c index 7cd3a2a954ff7d70e6ba7a6f7538648841bc54b2..f89b7158218be60ac10e61484a2d5e5e28a3182f 100644 --- a/deps/uv/src/unix/core.c +++ b/deps/uv/src/unix/core.c @@ -887,6 +887,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) { loop->watchers[w->fd] = w; loop->nfds++; } + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -918,6 +921,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) { } else if (QUEUE_EMPTY(&w->watcher_queue)) QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } @@ -934,6 +940,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) { void uv__io_feed(uv_loop_t* loop, uv__io_t* w) { if (QUEUE_EMPTY(&w->pending_queue)) QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue); + + if (uv__get_internal_fields(loop)->flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) + uv__loop_interrupt(loop); } diff --git a/deps/uv/src/unix/loop.c b/deps/uv/src/unix/loop.c index a88e71c339351f2ebcdd6c3f933fc3b1122910ed..353143e5ebecae598425dc036f4458bb7c43bb0b 100644 --- a/deps/uv/src/unix/loop.c +++ b/deps/uv/src/unix/loop.c @@ -217,6 +217,11 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + if (option != UV_LOOP_BLOCK_SIGNAL) return UV_ENOSYS; @@ -226,3 +231,37 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { loop->flags |= UV_LOOP_BLOCK_SIGPROF; return 0; } + + +void uv__loop_interrupt(uv_loop_t* loop) { + const void* buf; + ssize_t len; + int fd; + int r; + + buf = ""; + len = 1; + fd = loop->async_wfd; + +#if defined(__linux__) + if (fd == -1) { + static const uint64_t val = 1; + buf = &val; + len = sizeof(val); + fd = loop->async_io_watcher.fd; /* eventfd */ + } +#endif + + do + r = write(fd, buf, len); + while (r == -1 && errno == EINTR); + + if (r == len) + return; + + if (r == -1) + if (errno == EAGAIN || errno == EWOULDBLOCK) + return; + + abort(); +} diff --git a/deps/uv/src/uv-common.h b/deps/uv/src/uv-common.h index 6001b0cf68d0b0268b578218b664a737f43c9521..5d2212571f4bcb648ab332f0c5650d0fdb37c03a 100644 --- a/deps/uv/src/uv-common.h +++ b/deps/uv/src/uv-common.h @@ -140,6 +140,8 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap); void uv__loop_close(uv_loop_t* loop); +void uv__loop_interrupt(uv_loop_t* loop); + int uv__read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb); @@ -268,6 +270,10 @@ void uv__threadpool_cleanup(void); if (((h)->flags & UV_HANDLE_ACTIVE) != 0) break; \ (h)->flags |= UV_HANDLE_ACTIVE; \ if (((h)->flags & UV_HANDLE_REF) != 0) uv__active_handle_add(h); \ + int loop_flags = uv__get_internal_fields((h)->loop)->flags; \ + if (loop_flags & UV_LOOP_INTERRUPT_ON_IO_CHANGE) { \ + uv__loop_interrupt((h)->loop); \ + } \ } \ while (0) diff --git a/deps/uv/src/win/core.c b/deps/uv/src/win/core.c index e53a0f8e28637a58ceec7852d1a79874fc1a9548..dd4065c1cc68763bfe258492e3119669311394dc 100644 --- a/deps/uv/src/win/core.c +++ b/deps/uv/src/win/core.c @@ -381,10 +381,20 @@ int uv__loop_configure(uv_loop_t* loop, uv_loop_option option, va_list ap) { return 0; } + if (option == UV_LOOP_INTERRUPT_ON_IO_CHANGE) { + lfields->flags |= UV_LOOP_INTERRUPT_ON_IO_CHANGE; + return 0; + } + return UV_ENOSYS; } +void uv__loop_interrupt(uv_loop_t* loop) { + PostQueuedCompletionStatus(loop->iocp, 0, 0, NULL); +} + + int uv_backend_fd(const uv_loop_t* loop) { return -1; } diff --git a/deps/uv/test/test-embed.c b/deps/uv/test/test-embed.c index c6ddceb149d9c1d68b0dd17b6dac0d4c3c3e9dbc..f6572c5dc2b6ef39bd11889ad1f7873007a6437d 100644 --- a/deps/uv/test/test-embed.c +++ b/deps/uv/test/test-embed.c @@ -25,115 +25,179 @@ #include <stdlib.h> #include <errno.h> -#ifndef HAVE_KQUEUE -# if defined(__APPLE__) || \ - defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__FreeBSD_kernel__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) -# define HAVE_KQUEUE 1 -# endif -#endif - #ifndef HAVE_EPOLL # if defined(__linux__) # define HAVE_EPOLL 1 # endif #endif -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) +#if defined(HAVE_EPOLL) +# include <sys/epoll.h> +#endif -#if defined(HAVE_KQUEUE) +#if !defined(_WIN32) # include <sys/types.h> -# include <sys/event.h> # include <sys/time.h> #endif -#if defined(HAVE_EPOLL) -# include <sys/epoll.h> -#endif - +static uv_loop_t main_loop; +static uv_loop_t external_loop; static uv_thread_t embed_thread; static uv_sem_t embed_sem; -static uv_timer_t embed_timer; static uv_async_t embed_async; +static uv_async_t main_async; static volatile int embed_closed; -static int embed_timer_called; +static uv_timer_t main_timer; +static int main_timer_called; -static void embed_thread_runner(void* arg) { +#if defined(_WIN32) +static void embed_thread_poll_win(HANDLE iocp, int timeout) { + DWORD bytes; + ULONG_PTR key; + OVERLAPPED* overlapped; + + GetQueuedCompletionStatus(iocp, + &bytes, + &key, + &overlapped, + timeout >= 0 ? timeout : INFINITE); + + /* Give the event back so the loop can deal with it. */ + if (overlapped != NULL) + PostQueuedCompletionStatus(iocp, + bytes, + key, + overlapped); +} +#else +static void embed_thread_poll_unix(int fd, int timeout) { int r; - int fd; + do { +#if defined(HAVE_EPOLL) + struct epoll_event ev; + r = epoll_wait(fd, &ev, 1, timeout); +#else + struct timeval tv; + if (timeout >= 0) { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + } + fd_set readset; + FD_ZERO(&readset); + FD_SET(fd, &readset); + r = select(fd + 1, &readset, NULL, NULL, timeout >= 0 ? &tv : NULL); +#endif + } while (r == -1 && errno == EINTR); +} +#endif /* !_WIN32 */ + + +static void embed_thread_runner(void* arg) { int timeout; - while (!embed_closed) { - fd = uv_backend_fd(uv_default_loop()); - timeout = uv_backend_timeout(uv_default_loop()); - - do { -#if defined(HAVE_KQUEUE) - struct timespec ts; - ts.tv_sec = timeout / 1000; - ts.tv_nsec = (timeout % 1000) * 1000000; - r = kevent(fd, NULL, 0, NULL, 0, &ts); -#elif defined(HAVE_EPOLL) - { - struct epoll_event ev; - r = epoll_wait(fd, &ev, 1, timeout); - } + do { + timeout = uv_backend_timeout(&main_loop); + +#if defined(_WIN32) + embed_thread_poll_win(main_loop.iocp, timeout); +#else + embed_thread_poll_unix(uv_backend_fd(&main_loop), timeout); #endif - } while (r == -1 && errno == EINTR); + uv_async_send(&embed_async); + uv_sem_wait(&embed_sem); - } + } while (!embed_closed); } static void embed_cb(uv_async_t* async) { - uv_run(uv_default_loop(), UV_RUN_ONCE); + /* Run tasks in main loop */ + uv_run(&main_loop, UV_RUN_NOWAIT); + /* Tell embed thread to continue polling */ uv_sem_post(&embed_sem); } -static void embed_timer_cb(uv_timer_t* timer) { - embed_timer_called++; +static void main_timer_cb(uv_timer_t* timer) { + main_timer_called++; embed_closed = 1; uv_close((uv_handle_t*) &embed_async, NULL); + uv_close((uv_handle_t*) &main_async, NULL); } -#endif -TEST_IMPL(embed) { -#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL) - uv_loop_t external; - - ASSERT(0 == uv_loop_init(&external)); +static void init_loops(void) { + ASSERT_EQ(0, uv_loop_init(&main_loop)); + ASSERT_EQ(0, uv_loop_init(&external_loop)); - embed_timer_called = 0; + main_timer_called = 0; embed_closed = 0; - uv_async_init(&external, &embed_async, embed_cb); + uv_async_init(&external_loop, &embed_async, embed_cb); - /* Start timer in default loop */ - uv_timer_init(uv_default_loop(), &embed_timer); - uv_timer_start(&embed_timer, embed_timer_cb, 250, 0); + /* Create a dummy async for main loop otherwise backend timeout will + always be 0 */ + uv_async_init(&main_loop, &main_async, embed_cb); - /* Start worker that will interrupt external loop */ + /* Start worker that will poll main loop and interrupt external loop */ uv_sem_init(&embed_sem, 0); uv_thread_create(&embed_thread, embed_thread_runner, NULL); +} - /* But run external loop */ - uv_run(&external, UV_RUN_DEFAULT); + +static void run_loop(void) { + /* Run external loop */ + uv_run(&external_loop, UV_RUN_DEFAULT); uv_thread_join(&embed_thread); - uv_loop_close(&external); + uv_sem_destroy(&embed_sem); + uv_loop_close(&external_loop); + uv_loop_close(&main_loop); +} - ASSERT(embed_timer_called == 1); -#endif + +TEST_IMPL(embed) { + init_loops(); + + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); + + return 0; +} + + +static uv_timer_t external_timer; + + +static void external_timer_cb(uv_timer_t* timer) { + /* Start timer in main loop */ + uv_timer_init(&main_loop, &main_timer); + uv_timer_start(&main_timer, main_timer_cb, 250, 0); +} + + +TEST_IMPL(embed_with_external_timer) { + init_loops(); + + /* Interrupt embed polling when a handle is started */ + ASSERT_EQ(0, uv_loop_configure(&main_loop, UV_LOOP_INTERRUPT_ON_IO_CHANGE)); + + /* Start timer in external loop, whose callback will not interrupt the + polling in embed thread */ + uv_timer_init(&external_loop, &external_timer); + uv_timer_start(&external_timer, external_timer_cb, 100, 0); + + run_loop(); + ASSERT_EQ(main_timer_called, 1); return 0; } diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h index a43edf1a4a9b0932ec73b8edaca0f676ecf3ccfa..199402e31406cf8ba360d54769461bb5285011ee 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h @@ -263,6 +263,7 @@ TEST_DECLARE (process_priority) TEST_DECLARE (has_ref) TEST_DECLARE (active) TEST_DECLARE (embed) +TEST_DECLARE (embed_with_external_timer) TEST_DECLARE (async) TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) @@ -860,6 +861,7 @@ TASK_LIST_START TEST_ENTRY (active) TEST_ENTRY (embed) + TEST_ENTRY (embed_with_external_timer) TEST_ENTRY (async) TEST_ENTRY (async_null_cb)
closed
electron/electron
https://github.com/electron/electron
35,384
[Bug]: Mac crash on WebWorker destructor
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? macOS ### Operating System Version 12.3 ### What arch are you using? x64 ### Last Known Working Electron version 20.0.2 ### Expected Behavior When destructing WebWorkers, it should not crash ### Actual Behavior When destructing a WebWorker that uses WebAssembly, it crashes the v8 context. ### Testcase Gist URL _No response_ ### Additional Information It seems linked to the recent change to the "stop_and_close_uv_loop" change, seen here: #35322 If I revert that single change, it does not crash. Attached is a minidump [minidump.zip](https://github.com/electron/electron/files/9382529/e9384a04-0947-4e26-b452-c85e84309bf9.zip)
https://github.com/electron/electron/issues/35384
https://github.com/electron/electron/pull/35422
2f23bdb19ea76029907ae247cc8eb47114df1d0c
18475818486be806e891e8e6cb13b83c620ec0aa
2022-08-19T13:30:36Z
c++
2022-08-29T13:45:48Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #if !defined(MAS_BUILD) #include "shell/common/crash_keys.h" #endif #define ELECTRON_BUILTIN_MODULES(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_dialog) \ V(electron_browser_event) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_VIEWS_MODULES(V) V(electron_browser_image_view) #define ELECTRON_DESKTOP_CAPTURER_MODULE(V) V(electron_browser_desktop_capturer) #define ELECTRON_TESTING_MODULE(V) V(electron_common_testing) // This is used to load built-in modules. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in modules explicitly. This is only // forward declaration. The definitions are in each module's // implementation when calling the NODE_LINKED_MODULE_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); uv_loop_close(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !defined(MAS_BUILD) electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String>) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. v8::Isolate* isolate = context->GetIsolate(); if (node::Environment::GetCurrent(isolate) == nullptr) { if (gin_helper::Locker::IsBrowserProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, v8::String::Empty(isolate)); } return node::AllowWasmCodeGenerationCallback(context, v8::String::Empty(isolate)); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); gin_helper::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } const std::unordered_set<base::StringPiece, base::StringPieceHash> GetAllowedDebugOptions() { if (electron::fuses::IsNodeCliInspectEnabled()) { // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode return { "--inspect", "--inspect-brk", "--inspect-port", "--debug", "--debug-brk", "--debug-port", "--inspect-brk-node", "--inspect-publish-uid", }; } // If node CLI inspect support is disabled, allow no debug options. return {}; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void SetNodeCliFlags() { const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = GetAllowedDebugOptions(); const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (allowed.count(stripped) != 0 || stripped == "--") args.push_back(option); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed const std::set<std::string> disallowed = { "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", "--force-fips", "--enable-fips"}; // Subset of options allowed in packaged apps const std::set<std::string> allowed_in_packaged = {"--max-http-header-size", "--http-parser"}; if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && allowed_in_packaged.find(option) == allowed_in_packaged.end()) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.find(option) != disallowed.end()) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinModules() { #define V(modname) _register_##modname(); ELECTRON_BUILTIN_MODULES(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_MODULES(V) #endif #if BUILDFLAG(ENABLE_DESKTOP_CAPTURER) ELECTRON_DESKTOP_CAPTURER_MODULE(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_MODULE(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin modules. RegisterBuiltinModules(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& atom_args = ElectronCommandLine::argv(); std::vector<std::string> args(atom_args.size()); std::transform(atom_args.cbegin(), atom_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); // Do not set DOM globals for renderer process. // We must set this before the node bootstrapper which is run inside // CreateEnvironment if (browser_env_ != BrowserEnvironment::kBrowser) global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } std::vector<std::string> exec_args; base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ != BrowserEnvironment::kBrowser) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } DCHECK(env); // Clean up the global _noBrowserGlobals that we unironically injected into // the global scope if (browser_env_ != BrowserEnvironment::kBrowser) { // We need to bootstrap the env in non-browser processes so that // _noBrowserGlobals is read correctly before we remove it global.Delete("_noBrowserGlobals"); } node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; if (browser_env_ == BrowserEnvironment::kBrowser) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::ThreadTaskRunnerHandle::Get(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. auto old_policy = env->isolate()->GetMicrotasksPolicy(); DCHECK_EQ(v8::MicrotasksScope::GetCurrentDepth(env->isolate()), 0); env->isolate()->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); env->isolate()->SetMicrotasksPolicy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,880
[Bug]: Devtools opened at bottom for browserView webcontents is not fully visible
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When devTools is opened with mode:"bottom" , it should be able show view without hiding the bottom views. For eg. in network tab, user should able to scroll till last entry in the table and that should be clearly visible. ### Actual Behavior ![image](https://user-images.githubusercontent.com/12984605/153824335-a4374015-42f5-4e7a-b852-bc1d559b5ce9.png) - Currently devTools for browserView webContents is not fully visible while trying to scroll at fullest. View is cutting from bottom for last few entries and view. Same happens with other dev tools tab. ### Testcase Gist URL https://gist.github.com/b1238af9836d6c034c1ff4ec2e22564b ### Additional Information _No response_
https://github.com/electron/electron/issues/32880
https://github.com/electron/electron/pull/34713
d0e220cbcecb6fcca6b6e8acf161dd51864718f2
75f9573e53338e15af7c7ccd07a529332847ea2c
2022-02-14T08:14:26Z
c++
2022-08-29T15:53:03Z
shell/browser/native_browser_view_mac.mm
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_mac.h" #import <objc/runtime.h> #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "skia/ext/skia_utils_mac.h" #include "ui/gfx/geometry/rect.h" // Match view::Views behavior where the view sticks to the top-left origin. const NSAutoresizingMaskOptions kDefaultAutoResizingMask = NSViewMaxXMargin | NSViewMinYMargin; @interface DragRegionView : NSView @property(assign) NSPoint initialLocation; @end @interface NSWindow () - (void)performWindowDragWithEvent:(NSEvent*)event; @end @implementation DragRegionView @synthesize initialLocation; + (void)load { if (getenv("ELECTRON_DEBUG_DRAG_REGIONS")) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL originalSelector = @selector(drawRect:); SEL swizzledSelector = @selector(drawDebugRect:); Method originalMethod = class_getInstanceMethod([self class], originalSelector); Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector); BOOL didAddMethod = class_addMethod([self class], originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) { class_replaceMethod([self class], swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } }); } } - (BOOL)mouseDownCanMoveWindow { return [self.window respondsToSelector:@selector(performWindowDragWithEvent:)]; } - (BOOL)acceptsFirstMouse:(NSEvent*)event { return YES; } - (BOOL)shouldIgnoreMouseEvent { NSEventType type = [[NSApp currentEvent] type]; return type != NSEventTypeLeftMouseDragged && type != NSEventTypeLeftMouseDown; } - (NSView*)hitTest:(NSPoint)point { // Pass-through events that hit one of the exclusion zones for (NSView* exclusion_zones in [self subviews]) { if ([exclusion_zones hitTest:point]) return nil; } return self; } - (void)mouseDown:(NSEvent*)event { [super mouseDown:event]; if ([self.window respondsToSelector:@selector(performWindowDragWithEvent:)]) { // According to Google, using performWindowDragWithEvent: // does not generate a NSWindowWillMoveNotification. Hence post one. [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowWillMoveNotification object:self]; [self.window performWindowDragWithEvent:event]; return; } if (self.window.styleMask & NSWindowStyleMaskFullScreen) { return; } self.initialLocation = [event locationInWindow]; } - (void)mouseDragged:(NSEvent*)event { if ([self.window respondsToSelector:@selector(performWindowDragWithEvent:)]) { return; } if (self.window.styleMask & NSWindowStyleMaskFullScreen) { return; } NSPoint currentLocation = [NSEvent mouseLocation]; NSPoint newOrigin; NSRect screenFrame = [[NSScreen mainScreen] frame]; NSSize screenSize = screenFrame.size; NSRect windowFrame = [self.window frame]; NSSize windowSize = windowFrame.size; newOrigin.x = currentLocation.x - self.initialLocation.x; newOrigin.y = currentLocation.y - self.initialLocation.y; BOOL inMenuBar = (newOrigin.y + windowSize.height) > (screenFrame.origin.y + screenSize.height); BOOL screenAboveMainScreen = false; if (inMenuBar) { for (NSScreen* screen in [NSScreen screens]) { NSRect currentScreenFrame = [screen frame]; BOOL isHigher = currentScreenFrame.origin.y > screenFrame.origin.y; // If there's another screen that is generally above the current screen, // we'll draw a new rectangle that is just above the current screen. If // the "higher" screen intersects with this rectangle, we'll allow drawing // above the menubar. if (isHigher) { NSRect aboveScreenRect = NSMakeRect(screenFrame.origin.x, screenFrame.origin.y + screenFrame.size.height - 10, screenFrame.size.width, 200); BOOL screenAboveIntersects = NSIntersectsRect(currentScreenFrame, aboveScreenRect); if (screenAboveIntersects) { screenAboveMainScreen = true; break; } } } } // Don't let window get dragged up under the menu bar if (inMenuBar && !screenAboveMainScreen) { newOrigin.y = screenFrame.origin.y + (screenFrame.size.height - windowFrame.size.height); } // Move the window to the new location [self.window setFrameOrigin:newOrigin]; } // For debugging purposes only. - (void)drawDebugRect:(NSRect)aRect { [[[NSColor greenColor] colorWithAlphaComponent:0.5] set]; NSRectFill([self bounds]); } @end @interface ExcludeDragRegionView : NSView @end @implementation ExcludeDragRegionView + (void)load { if (getenv("ELECTRON_DEBUG_DRAG_REGIONS")) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL originalSelector = @selector(drawRect:); SEL swizzledSelector = @selector(drawDebugRect:); Method originalMethod = class_getInstanceMethod([self class], originalSelector); Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector); BOOL didAddMethod = class_addMethod([self class], originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) { class_replaceMethod([self class], swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } }); } } - (BOOL)mouseDownCanMoveWindow { return NO; } // For debugging purposes only. - (void)drawDebugRect:(NSRect)aRect { [[[NSColor redColor] colorWithAlphaComponent:0.5] set]; NSRectFill([self bounds]); } @end namespace electron { NativeBrowserViewMac::NativeBrowserViewMac( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = kDefaultAutoResizingMask; } NativeBrowserViewMac::~NativeBrowserViewMac() = default; void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) { NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask; if (flags & kAutoResizeWidth) { autoresizing_mask |= NSViewWidthSizable; } if (flags & kAutoResizeHeight) { autoresizing_mask |= NSViewHeightSizable; } if (flags & kAutoResizeHorizontal) { autoresizing_mask |= NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable; } if (flags & kAutoResizeVertical) { autoresizing_mask |= NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable; } auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = autoresizing_mask; } void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); auto* superview = view.superview; const auto superview_height = superview ? superview.frame.size.height : 0; view.frame = NSMakeRect(bounds.x(), superview_height - bounds.y() - bounds.height(), bounds.width(), bounds.height()); // Ensure draggable regions are properly updated to reflect new bounds. UpdateDraggableRegions(draggable_regions_); } gfx::Rect NativeBrowserViewMac::GetBounds() { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); NSView* view = iwc_view->GetNativeView().GetNativeNSView(); const int superview_height = (view.superview) ? view.superview.frame.size.height : 0; return gfx::Rect( view.frame.origin.x, superview_height - view.frame.origin.y - view.frame.size.height, view.frame.size.width, view.frame.size.height); } void NativeBrowserViewMac::SetBackgroundColor(SkColor color) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.wantsLayer = YES; view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color); } void NativeBrowserViewMac::UpdateDraggableRegions( const std::vector<gfx::Rect>& drag_exclude_rects) { if (!inspectable_web_contents_) return; auto* web_contents = inspectable_web_contents_->GetWebContents(); auto* iwc_view = GetInspectableWebContentsView(); NSView* web_view = web_contents->GetNativeView().GetNativeNSView(); NSView* inspectable_view = iwc_view->GetNativeView().GetNativeNSView(); NSView* window_content_view = inspectable_view.superview; // Remove all DragRegionViews that were added last time. Note that we need // to copy the `subviews` array to avoid mutation during iteration. base::scoped_nsobject<NSArray> subviews([[web_view subviews] copy]); for (NSView* subview in subviews.get()) { if ([subview isKindOfClass:[DragRegionView class]]) { [subview removeFromSuperview]; } } // Create one giant NSView that is draggable. base::scoped_nsobject<NSView> drag_region_view( [[DragRegionView alloc] initWithFrame:web_view.bounds]); [web_view addSubview:drag_region_view]; // Then, on top of that, add "exclusion zones". auto const offset = GetBounds().OffsetFromOrigin(); const auto window_content_view_height = NSHeight(window_content_view.bounds); for (const auto& rect : drag_exclude_rects) { const auto x = rect.x() + offset.x(); const auto y = window_content_view_height - (rect.bottom() + offset.y()); const auto exclude_rect = NSMakeRect(x, y, rect.width(), rect.height()); const auto drag_region_view_exclude_rect = [window_content_view convertRect:exclude_rect toView:drag_region_view]; base::scoped_nsobject<NSView> exclude_drag_region_view( [[ExcludeDragRegionView alloc] initWithFrame:drag_region_view_exclude_rect]); [drag_region_view addSubview:exclude_drag_region_view]; } } void NativeBrowserViewMac::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { if (!inspectable_web_contents_) return; auto* web_contents = inspectable_web_contents_->GetWebContents(); NSView* web_view = web_contents->GetNativeView().GetNativeNSView(); NSInteger webViewWidth = NSWidth([web_view bounds]); NSInteger webViewHeight = NSHeight([web_view bounds]); // Draggable regions are implemented by having the whole web view draggable // and overlaying regions that are not draggable. if (&draggable_regions_ != &regions) draggable_regions_ = mojo::Clone(regions); std::vector<gfx::Rect> drag_exclude_rects; if (draggable_regions_.empty()) { drag_exclude_rects.emplace_back(0, 0, webViewWidth, webViewHeight); } else { drag_exclude_rects = CalculateNonDraggableRegions( DraggableRegionsToSkRegion(draggable_regions_), webViewWidth, webViewHeight); } UpdateDraggableRegions(drag_exclude_rects); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewMac(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,880
[Bug]: Devtools opened at bottom for browserView webcontents is not fully visible
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When devTools is opened with mode:"bottom" , it should be able show view without hiding the bottom views. For eg. in network tab, user should able to scroll till last entry in the table and that should be clearly visible. ### Actual Behavior ![image](https://user-images.githubusercontent.com/12984605/153824335-a4374015-42f5-4e7a-b852-bc1d559b5ce9.png) - Currently devTools for browserView webContents is not fully visible while trying to scroll at fullest. View is cutting from bottom for last few entries and view. Same happens with other dev tools tab. ### Testcase Gist URL https://gist.github.com/b1238af9836d6c034c1ff4ec2e22564b ### Additional Information _No response_
https://github.com/electron/electron/issues/32880
https://github.com/electron/electron/pull/34713
d0e220cbcecb6fcca6b6e8acf161dd51864718f2
75f9573e53338e15af7c7ccd07a529332847ea2c
2022-02-14T08:14:26Z
c++
2022-08-29T15:53:03Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'path'; import { emittedOnce } from './events-helpers'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './window-helpers'; import { defer, ifit, startRemoteControlApp } from './spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './screen-helpers'; describe('BrowserView module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); let w: BrowserWindow; let view: BrowserView; beforeEach(() => { expect(webContents.getAllWebContents()).to.have.length(0); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }); }); afterEach(async () => { const p = emittedOnce(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view) { const p = emittedOnce(view.webContents, 'destroyed'); (view.webContents as any).destroy(); view = null as any; await p; } expect(webContents.getAllWebContents()).to.have.length(0); }); it('can be created with an existing webContents', async () => { const wc = (webContents as any).create({ sandbox: true }); await wc.loadURL('about:blank'); view = new BrowserView({ webContents: wc } as any); expect(view.webContents.getURL()).to.equal('about:blank'); }); describe('BrowserView.setBackgroundColor()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBackgroundColor('#000'); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBackgroundColor(null as any); }).to.throw(/conversion failure/); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('sets the background color to transparent if none is set', async () => { const display = screen.getPrimaryDisplay(); const WINDOW_BACKGROUND_COLOR = '#55ccbb'; w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('successfully applies the background color', async () => { const WINDOW_BACKGROUND_COLOR = '#55ccbb'; const VIEW_BACKGROUND_COLOR = '#ff00ff'; const display = screen.getPrimaryDisplay(); w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); w.setBackgroundColor(VIEW_BACKGROUND_COLOR); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true(); }); }); describe('BrowserView.setAutoResize()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setAutoResize({}); view.setAutoResize({ width: true, height: false }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setAutoResize(null as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.setBounds()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBounds({ x: 0, y: 0, width: 1, height: 1 }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBounds(null as any); }).to.throw(/conversion failure/); expect(() => { view.setBounds({} as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.getBounds()', () => { it('returns the current bounds', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); }); describe('BrowserWindow.setBrowserView()', () => { it('does not throw for valid args', () => { view = new BrowserView(); w.setBrowserView(view); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.setBrowserView(view); w.setBrowserView(view); w.setBrowserView(view); }); }); describe('BrowserWindow.getBrowserView()', () => { it('returns the set view', () => { view = new BrowserView(); w.setBrowserView(view); const view2 = w.getBrowserView(); expect(view2!.webContents.id).to.equal(view.webContents.id); }); it('returns null if none is set', () => { const view = w.getBrowserView(); expect(view).to.be.null('view'); }); }); describe('BrowserWindow.addBrowserView()', () => { it('does not throw for valid args', () => { const view1 = new BrowserView(); defer(() => (view1.webContents as any).destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => (view2.webContents as any).destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.addBrowserView(view); w.addBrowserView(view); w.addBrowserView(view); }); it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => { expect(() => { const view1 = new BrowserView(); (view1.webContents as any).destroy(); w.addBrowserView(view1); }).to.not.throw(); }); it('does not crash if the webContents is destroyed after a URL is loaded', () => { view = new BrowserView(); expect(async () => { view.setBounds({ x: 0, y: 0, width: 400, height: 300 }); await view.webContents.loadURL('data:text/html,hello there'); view.webContents.destroy(); }).to.not.throw(); }); it('can handle BrowserView reparenting', async () => { view = new BrowserView(); w.addBrowserView(view); view.webContents.loadURL('about:blank'); await emittedOnce(view.webContents, 'did-finish-load'); const w2 = new BrowserWindow({ show: false }); w2.addBrowserView(view); w.close(); view.webContents.loadURL(`file://${fixtures}/pages/blank.html`); await emittedOnce(view.webContents, 'did-finish-load'); // Clean up - the afterEach hook assumes the webContents on w is still alive. w = new BrowserWindow({ show: false }); w2.close(); w2.destroy(); }); }); describe('BrowserWindow.removeBrowserView()', () => { it('does not throw if called multiple times with same view', () => { expect(() => { view = new BrowserView(); w.addBrowserView(view); w.removeBrowserView(view); w.removeBrowserView(view); }).to.not.throw(); }); }); describe('BrowserWindow.getBrowserViews()', () => { it('returns same views as was added', () => { const view1 = new BrowserView(); defer(() => (view1.webContents as any).destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => (view2.webContents as any).destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view1.webContents.id); expect(views[1].webContents.id).to.equal(view2.webContents.id); }); }); describe('BrowserWindow.setTopBrowserView()', () => { it('should throw an error when a BrowserView is not attached to the window', () => { view = new BrowserView(); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); }); it('should throw an error when a BrowserView is attached to some other window', () => { view = new BrowserView(); const win2 = new BrowserWindow(); w.addBrowserView(view); view.setBounds({ x: 0, y: 0, width: 100, height: 100 }); win2.addBrowserView(view); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); win2.close(); win2.destroy(); }); }); describe('BrowserView.webContents.getOwnerBrowserWindow()', () => { it('points to owning window', () => { view = new BrowserView(); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); w.setBrowserView(view); expect(view.webContents.getOwnerBrowserWindow()).to.equal(w); w.setBrowserView(null); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); }); }); describe('shutdown behavior', () => { it('does not crash on exit', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { BrowserView, app } = require('electron'); new BrowserView({}) // eslint-disable-line setTimeout(() => { app.quit(); }); }); const [code] = await emittedOnce(rc.process, 'exit'); expect(code).to.equal(0); }); it('does not crash on exit if added to a browser window', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { app, BrowserView, BrowserWindow } = require('electron'); const bv = new BrowserView(); bv.webContents.loadURL('about:blank'); const bw = new BrowserWindow({ show: false }); bw.addBrowserView(bv); setTimeout(() => { app.quit(); }); }); const [code] = await emittedOnce(rc.process, 'exit'); expect(code).to.equal(0); }); }); describe('window.open()', () => { it('works in BrowserView', (done) => { view = new BrowserView(); w.setBrowserView(view); view.webContents.setWindowOpenHandler(({ url, frameName }) => { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); done(); return { action: 'deny' }; }); view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); }); describe('BrowserView.capturePage(rect)', () => { it('returns a Promise with a Buffer', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.addBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); const image = await view.webContents.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); xit('resolves after the window is hidden and capturer count is non-zero', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.incrementCapturerCount(); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('should increase the capturer count', () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); view.webContents.incrementCapturerCount(); expect(view.webContents.isBeingCaptured()).to.be.true(); view.webContents.decrementCapturerCount(); expect(view.webContents.isBeingCaptured()).to.be.false(); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,880
[Bug]: Devtools opened at bottom for browserView webcontents is not fully visible
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When devTools is opened with mode:"bottom" , it should be able show view without hiding the bottom views. For eg. in network tab, user should able to scroll till last entry in the table and that should be clearly visible. ### Actual Behavior ![image](https://user-images.githubusercontent.com/12984605/153824335-a4374015-42f5-4e7a-b852-bc1d559b5ce9.png) - Currently devTools for browserView webContents is not fully visible while trying to scroll at fullest. View is cutting from bottom for last few entries and view. Same happens with other dev tools tab. ### Testcase Gist URL https://gist.github.com/b1238af9836d6c034c1ff4ec2e22564b ### Additional Information _No response_
https://github.com/electron/electron/issues/32880
https://github.com/electron/electron/pull/34713
d0e220cbcecb6fcca6b6e8acf161dd51864718f2
75f9573e53338e15af7c7ccd07a529332847ea2c
2022-02-14T08:14:26Z
c++
2022-08-29T15:53:03Z
shell/browser/native_browser_view_mac.mm
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_mac.h" #import <objc/runtime.h> #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "skia/ext/skia_utils_mac.h" #include "ui/gfx/geometry/rect.h" // Match view::Views behavior where the view sticks to the top-left origin. const NSAutoresizingMaskOptions kDefaultAutoResizingMask = NSViewMaxXMargin | NSViewMinYMargin; @interface DragRegionView : NSView @property(assign) NSPoint initialLocation; @end @interface NSWindow () - (void)performWindowDragWithEvent:(NSEvent*)event; @end @implementation DragRegionView @synthesize initialLocation; + (void)load { if (getenv("ELECTRON_DEBUG_DRAG_REGIONS")) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL originalSelector = @selector(drawRect:); SEL swizzledSelector = @selector(drawDebugRect:); Method originalMethod = class_getInstanceMethod([self class], originalSelector); Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector); BOOL didAddMethod = class_addMethod([self class], originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) { class_replaceMethod([self class], swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } }); } } - (BOOL)mouseDownCanMoveWindow { return [self.window respondsToSelector:@selector(performWindowDragWithEvent:)]; } - (BOOL)acceptsFirstMouse:(NSEvent*)event { return YES; } - (BOOL)shouldIgnoreMouseEvent { NSEventType type = [[NSApp currentEvent] type]; return type != NSEventTypeLeftMouseDragged && type != NSEventTypeLeftMouseDown; } - (NSView*)hitTest:(NSPoint)point { // Pass-through events that hit one of the exclusion zones for (NSView* exclusion_zones in [self subviews]) { if ([exclusion_zones hitTest:point]) return nil; } return self; } - (void)mouseDown:(NSEvent*)event { [super mouseDown:event]; if ([self.window respondsToSelector:@selector(performWindowDragWithEvent:)]) { // According to Google, using performWindowDragWithEvent: // does not generate a NSWindowWillMoveNotification. Hence post one. [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowWillMoveNotification object:self]; [self.window performWindowDragWithEvent:event]; return; } if (self.window.styleMask & NSWindowStyleMaskFullScreen) { return; } self.initialLocation = [event locationInWindow]; } - (void)mouseDragged:(NSEvent*)event { if ([self.window respondsToSelector:@selector(performWindowDragWithEvent:)]) { return; } if (self.window.styleMask & NSWindowStyleMaskFullScreen) { return; } NSPoint currentLocation = [NSEvent mouseLocation]; NSPoint newOrigin; NSRect screenFrame = [[NSScreen mainScreen] frame]; NSSize screenSize = screenFrame.size; NSRect windowFrame = [self.window frame]; NSSize windowSize = windowFrame.size; newOrigin.x = currentLocation.x - self.initialLocation.x; newOrigin.y = currentLocation.y - self.initialLocation.y; BOOL inMenuBar = (newOrigin.y + windowSize.height) > (screenFrame.origin.y + screenSize.height); BOOL screenAboveMainScreen = false; if (inMenuBar) { for (NSScreen* screen in [NSScreen screens]) { NSRect currentScreenFrame = [screen frame]; BOOL isHigher = currentScreenFrame.origin.y > screenFrame.origin.y; // If there's another screen that is generally above the current screen, // we'll draw a new rectangle that is just above the current screen. If // the "higher" screen intersects with this rectangle, we'll allow drawing // above the menubar. if (isHigher) { NSRect aboveScreenRect = NSMakeRect(screenFrame.origin.x, screenFrame.origin.y + screenFrame.size.height - 10, screenFrame.size.width, 200); BOOL screenAboveIntersects = NSIntersectsRect(currentScreenFrame, aboveScreenRect); if (screenAboveIntersects) { screenAboveMainScreen = true; break; } } } } // Don't let window get dragged up under the menu bar if (inMenuBar && !screenAboveMainScreen) { newOrigin.y = screenFrame.origin.y + (screenFrame.size.height - windowFrame.size.height); } // Move the window to the new location [self.window setFrameOrigin:newOrigin]; } // For debugging purposes only. - (void)drawDebugRect:(NSRect)aRect { [[[NSColor greenColor] colorWithAlphaComponent:0.5] set]; NSRectFill([self bounds]); } @end @interface ExcludeDragRegionView : NSView @end @implementation ExcludeDragRegionView + (void)load { if (getenv("ELECTRON_DEBUG_DRAG_REGIONS")) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL originalSelector = @selector(drawRect:); SEL swizzledSelector = @selector(drawDebugRect:); Method originalMethod = class_getInstanceMethod([self class], originalSelector); Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector); BOOL didAddMethod = class_addMethod([self class], originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) { class_replaceMethod([self class], swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, swizzledMethod); } }); } } - (BOOL)mouseDownCanMoveWindow { return NO; } // For debugging purposes only. - (void)drawDebugRect:(NSRect)aRect { [[[NSColor redColor] colorWithAlphaComponent:0.5] set]; NSRectFill([self bounds]); } @end namespace electron { NativeBrowserViewMac::NativeBrowserViewMac( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = kDefaultAutoResizingMask; } NativeBrowserViewMac::~NativeBrowserViewMac() = default; void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) { NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask; if (flags & kAutoResizeWidth) { autoresizing_mask |= NSViewWidthSizable; } if (flags & kAutoResizeHeight) { autoresizing_mask |= NSViewHeightSizable; } if (flags & kAutoResizeHorizontal) { autoresizing_mask |= NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable; } if (flags & kAutoResizeVertical) { autoresizing_mask |= NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable; } auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.autoresizingMask = autoresizing_mask; } void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); auto* superview = view.superview; const auto superview_height = superview ? superview.frame.size.height : 0; view.frame = NSMakeRect(bounds.x(), superview_height - bounds.y() - bounds.height(), bounds.width(), bounds.height()); // Ensure draggable regions are properly updated to reflect new bounds. UpdateDraggableRegions(draggable_regions_); } gfx::Rect NativeBrowserViewMac::GetBounds() { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); NSView* view = iwc_view->GetNativeView().GetNativeNSView(); const int superview_height = (view.superview) ? view.superview.frame.size.height : 0; return gfx::Rect( view.frame.origin.x, superview_height - view.frame.origin.y - view.frame.size.height, view.frame.size.width, view.frame.size.height); } void NativeBrowserViewMac::SetBackgroundColor(SkColor color) { auto* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetNativeView().GetNativeNSView(); view.wantsLayer = YES; view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color); } void NativeBrowserViewMac::UpdateDraggableRegions( const std::vector<gfx::Rect>& drag_exclude_rects) { if (!inspectable_web_contents_) return; auto* web_contents = inspectable_web_contents_->GetWebContents(); auto* iwc_view = GetInspectableWebContentsView(); NSView* web_view = web_contents->GetNativeView().GetNativeNSView(); NSView* inspectable_view = iwc_view->GetNativeView().GetNativeNSView(); NSView* window_content_view = inspectable_view.superview; // Remove all DragRegionViews that were added last time. Note that we need // to copy the `subviews` array to avoid mutation during iteration. base::scoped_nsobject<NSArray> subviews([[web_view subviews] copy]); for (NSView* subview in subviews.get()) { if ([subview isKindOfClass:[DragRegionView class]]) { [subview removeFromSuperview]; } } // Create one giant NSView that is draggable. base::scoped_nsobject<NSView> drag_region_view( [[DragRegionView alloc] initWithFrame:web_view.bounds]); [web_view addSubview:drag_region_view]; // Then, on top of that, add "exclusion zones". auto const offset = GetBounds().OffsetFromOrigin(); const auto window_content_view_height = NSHeight(window_content_view.bounds); for (const auto& rect : drag_exclude_rects) { const auto x = rect.x() + offset.x(); const auto y = window_content_view_height - (rect.bottom() + offset.y()); const auto exclude_rect = NSMakeRect(x, y, rect.width(), rect.height()); const auto drag_region_view_exclude_rect = [window_content_view convertRect:exclude_rect toView:drag_region_view]; base::scoped_nsobject<NSView> exclude_drag_region_view( [[ExcludeDragRegionView alloc] initWithFrame:drag_region_view_exclude_rect]); [drag_region_view addSubview:exclude_drag_region_view]; } } void NativeBrowserViewMac::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { if (!inspectable_web_contents_) return; auto* web_contents = inspectable_web_contents_->GetWebContents(); NSView* web_view = web_contents->GetNativeView().GetNativeNSView(); NSInteger webViewWidth = NSWidth([web_view bounds]); NSInteger webViewHeight = NSHeight([web_view bounds]); // Draggable regions are implemented by having the whole web view draggable // and overlaying regions that are not draggable. if (&draggable_regions_ != &regions) draggable_regions_ = mojo::Clone(regions); std::vector<gfx::Rect> drag_exclude_rects; if (draggable_regions_.empty()) { drag_exclude_rects.emplace_back(0, 0, webViewWidth, webViewHeight); } else { drag_exclude_rects = CalculateNonDraggableRegions( DraggableRegionsToSkRegion(draggable_regions_), webViewWidth, webViewHeight); } UpdateDraggableRegions(drag_exclude_rects); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewMac(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,880
[Bug]: Devtools opened at bottom for browserView webcontents is not fully visible
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When devTools is opened with mode:"bottom" , it should be able show view without hiding the bottom views. For eg. in network tab, user should able to scroll till last entry in the table and that should be clearly visible. ### Actual Behavior ![image](https://user-images.githubusercontent.com/12984605/153824335-a4374015-42f5-4e7a-b852-bc1d559b5ce9.png) - Currently devTools for browserView webContents is not fully visible while trying to scroll at fullest. View is cutting from bottom for last few entries and view. Same happens with other dev tools tab. ### Testcase Gist URL https://gist.github.com/b1238af9836d6c034c1ff4ec2e22564b ### Additional Information _No response_
https://github.com/electron/electron/issues/32880
https://github.com/electron/electron/pull/34713
d0e220cbcecb6fcca6b6e8acf161dd51864718f2
75f9573e53338e15af7c7ccd07a529332847ea2c
2022-02-14T08:14:26Z
c++
2022-08-29T15:53:03Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'path'; import { emittedOnce } from './events-helpers'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './window-helpers'; import { defer, ifit, startRemoteControlApp } from './spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './screen-helpers'; describe('BrowserView module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); let w: BrowserWindow; let view: BrowserView; beforeEach(() => { expect(webContents.getAllWebContents()).to.have.length(0); w = new BrowserWindow({ show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }); }); afterEach(async () => { const p = emittedOnce(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view) { const p = emittedOnce(view.webContents, 'destroyed'); (view.webContents as any).destroy(); view = null as any; await p; } expect(webContents.getAllWebContents()).to.have.length(0); }); it('can be created with an existing webContents', async () => { const wc = (webContents as any).create({ sandbox: true }); await wc.loadURL('about:blank'); view = new BrowserView({ webContents: wc } as any); expect(view.webContents.getURL()).to.equal('about:blank'); }); describe('BrowserView.setBackgroundColor()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBackgroundColor('#000'); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBackgroundColor(null as any); }).to.throw(/conversion failure/); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('sets the background color to transparent if none is set', async () => { const display = screen.getPrimaryDisplay(); const WINDOW_BACKGROUND_COLOR = '#55ccbb'; w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('successfully applies the background color', async () => { const WINDOW_BACKGROUND_COLOR = '#55ccbb'; const VIEW_BACKGROUND_COLOR = '#ff00ff'; const display = screen.getPrimaryDisplay(); w.show(); w.setBounds(display.bounds); w.setBackgroundColor(WINDOW_BACKGROUND_COLOR); await w.loadURL('about:blank'); view = new BrowserView(); view.setBounds(display.bounds); w.setBrowserView(view); w.setBackgroundColor(VIEW_BACKGROUND_COLOR); await view.webContents.loadURL('data:text/html,hello there'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true(); }); }); describe('BrowserView.setAutoResize()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setAutoResize({}); view.setAutoResize({ width: true, height: false }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setAutoResize(null as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.setBounds()', () => { it('does not throw for valid args', () => { view = new BrowserView(); view.setBounds({ x: 0, y: 0, width: 1, height: 1 }); }); it('throws for invalid args', () => { view = new BrowserView(); expect(() => { view.setBounds(null as any); }).to.throw(/conversion failure/); expect(() => { view.setBounds({} as any); }).to.throw(/conversion failure/); }); }); describe('BrowserView.getBounds()', () => { it('returns the current bounds', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); }); describe('BrowserWindow.setBrowserView()', () => { it('does not throw for valid args', () => { view = new BrowserView(); w.setBrowserView(view); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.setBrowserView(view); w.setBrowserView(view); w.setBrowserView(view); }); }); describe('BrowserWindow.getBrowserView()', () => { it('returns the set view', () => { view = new BrowserView(); w.setBrowserView(view); const view2 = w.getBrowserView(); expect(view2!.webContents.id).to.equal(view.webContents.id); }); it('returns null if none is set', () => { const view = w.getBrowserView(); expect(view).to.be.null('view'); }); }); describe('BrowserWindow.addBrowserView()', () => { it('does not throw for valid args', () => { const view1 = new BrowserView(); defer(() => (view1.webContents as any).destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => (view2.webContents as any).destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); }); it('does not throw if called multiple times with same view', () => { view = new BrowserView(); w.addBrowserView(view); w.addBrowserView(view); w.addBrowserView(view); }); it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => { expect(() => { const view1 = new BrowserView(); (view1.webContents as any).destroy(); w.addBrowserView(view1); }).to.not.throw(); }); it('does not crash if the webContents is destroyed after a URL is loaded', () => { view = new BrowserView(); expect(async () => { view.setBounds({ x: 0, y: 0, width: 400, height: 300 }); await view.webContents.loadURL('data:text/html,hello there'); view.webContents.destroy(); }).to.not.throw(); }); it('can handle BrowserView reparenting', async () => { view = new BrowserView(); w.addBrowserView(view); view.webContents.loadURL('about:blank'); await emittedOnce(view.webContents, 'did-finish-load'); const w2 = new BrowserWindow({ show: false }); w2.addBrowserView(view); w.close(); view.webContents.loadURL(`file://${fixtures}/pages/blank.html`); await emittedOnce(view.webContents, 'did-finish-load'); // Clean up - the afterEach hook assumes the webContents on w is still alive. w = new BrowserWindow({ show: false }); w2.close(); w2.destroy(); }); }); describe('BrowserWindow.removeBrowserView()', () => { it('does not throw if called multiple times with same view', () => { expect(() => { view = new BrowserView(); w.addBrowserView(view); w.removeBrowserView(view); w.removeBrowserView(view); }).to.not.throw(); }); }); describe('BrowserWindow.getBrowserViews()', () => { it('returns same views as was added', () => { const view1 = new BrowserView(); defer(() => (view1.webContents as any).destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => (view2.webContents as any).destroy()); w.addBrowserView(view2); defer(() => w.removeBrowserView(view2)); const views = w.getBrowserViews(); expect(views).to.have.lengthOf(2); expect(views[0].webContents.id).to.equal(view1.webContents.id); expect(views[1].webContents.id).to.equal(view2.webContents.id); }); }); describe('BrowserWindow.setTopBrowserView()', () => { it('should throw an error when a BrowserView is not attached to the window', () => { view = new BrowserView(); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); }); it('should throw an error when a BrowserView is attached to some other window', () => { view = new BrowserView(); const win2 = new BrowserWindow(); w.addBrowserView(view); view.setBounds({ x: 0, y: 0, width: 100, height: 100 }); win2.addBrowserView(view); expect(() => { w.setTopBrowserView(view); }).to.throw(/is not attached/); win2.close(); win2.destroy(); }); }); describe('BrowserView.webContents.getOwnerBrowserWindow()', () => { it('points to owning window', () => { view = new BrowserView(); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); w.setBrowserView(view); expect(view.webContents.getOwnerBrowserWindow()).to.equal(w); w.setBrowserView(null); expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window'); }); }); describe('shutdown behavior', () => { it('does not crash on exit', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { BrowserView, app } = require('electron'); new BrowserView({}) // eslint-disable-line setTimeout(() => { app.quit(); }); }); const [code] = await emittedOnce(rc.process, 'exit'); expect(code).to.equal(0); }); it('does not crash on exit if added to a browser window', async () => { const rc = await startRemoteControlApp(); await rc.remotely(() => { const { app, BrowserView, BrowserWindow } = require('electron'); const bv = new BrowserView(); bv.webContents.loadURL('about:blank'); const bw = new BrowserWindow({ show: false }); bw.addBrowserView(bv); setTimeout(() => { app.quit(); }); }); const [code] = await emittedOnce(rc.process, 'exit'); expect(code).to.equal(0); }); }); describe('window.open()', () => { it('works in BrowserView', (done) => { view = new BrowserView(); w.setBrowserView(view); view.webContents.setWindowOpenHandler(({ url, frameName }) => { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); done(); return { action: 'deny' }; }); view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); }); describe('BrowserView.capturePage(rect)', () => { it('returns a Promise with a Buffer', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.addBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); const image = await view.webContents.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); xit('resolves after the window is hidden and capturer count is non-zero', async () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html')); view.webContents.incrementCapturerCount(); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('should increase the capturer count', () => { view = new BrowserView({ webPreferences: { backgroundThrottling: false } }); w.setBrowserView(view); view.setBounds({ ...w.getBounds(), x: 0, y: 0 }); view.webContents.incrementCapturerCount(); expect(view.webContents.isBeingCaptured()).to.be.true(); view.webContents.decrementCapturerCount(); expect(view.webContents.isBeingCaptured()).to.be.false(); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain } from 'electron/main'; import { AddressInfo } from 'net'; import * as ChildProcess from 'child_process'; import * as path from 'path'; import * as http from 'http'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as stream from 'stream'; import { EventEmitter } from 'events'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { WebmGenerator } from './video-helpers'; import { delay } from './spec-helpers'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerHttpProtocol = protocol.registerHttpProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { const body = new stream.PassThrough(); async function sendChunks () { await delay(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await delay(10); } body.push(null); } sendChunks(); return body; } // A promise that can be resolved externally. function defer (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as any).create({ sandbox: true }); }); after(() => (contents as any).destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); describe('protocol.registerStringProtocol', () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerBufferProtocol', () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerFileProtocol', () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it.skip('throws an error when custom headers are invalid', (done) => { registerFileProtocol(protocolName, (request, callback) => { expect(() => callback({ path: filePath, headers: { 'X-Great-Header': (42 as any) } })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string'); done(); }); ajax(protocolName + '://fake-host').catch(() => {}); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback(normalPath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerHttpProtocol', () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = 'http://127.0.0.1:' + port; registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); describe('protocol.registerStreamProtocol', () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = emittedOnce(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = emittedOnce(events, 'respond'); const hasClosedPromise = emittedOnce(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); server.listen(0, '127.0.0.1'); const port = (server.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}`; interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = defer(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const content = `<script>fetch("http://127.0.0.1:${port}")</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it.skip('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // FIXME: Figure out why this test is failing it.skip('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow = null as unknown as BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); });
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
spec/fixtures/pages/iframe-protocol.html
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain } from 'electron/main'; import { AddressInfo } from 'net'; import * as ChildProcess from 'child_process'; import * as path from 'path'; import * as http from 'http'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as stream from 'stream'; import { EventEmitter } from 'events'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { WebmGenerator } from './video-helpers'; import { delay } from './spec-helpers'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerHttpProtocol = protocol.registerHttpProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { const body = new stream.PassThrough(); async function sendChunks () { await delay(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await delay(10); } body.push(null); } sendChunks(); return body; } // A promise that can be resolved externally. function defer (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as any).create({ sandbox: true }); }); after(() => (contents as any).destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); describe('protocol.registerStringProtocol', () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerBufferProtocol', () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerFileProtocol', () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it.skip('throws an error when custom headers are invalid', (done) => { registerFileProtocol(protocolName, (request, callback) => { expect(() => callback({ path: filePath, headers: { 'X-Great-Header': (42 as any) } })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string'); done(); }); ajax(protocolName + '://fake-host').catch(() => {}); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback(normalPath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerHttpProtocol', () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = 'http://127.0.0.1:' + port; registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); describe('protocol.registerStreamProtocol', () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = emittedOnce(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = emittedOnce(events, 'respond'); const hasClosedPromise = emittedOnce(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); server.listen(0, '127.0.0.1'); const port = (server.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}`; interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = defer(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const content = `<script>fetch("http://127.0.0.1:${port}")</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it.skip('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // FIXME: Figure out why this test is failing it.skip('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow = null as unknown as BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); });
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
spec/fixtures/pages/iframe-protocol.html
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain } from 'electron/main'; import { AddressInfo } from 'net'; import * as ChildProcess from 'child_process'; import * as path from 'path'; import * as http from 'http'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as stream from 'stream'; import { EventEmitter } from 'events'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { WebmGenerator } from './video-helpers'; import { delay } from './spec-helpers'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerHttpProtocol = protocol.registerHttpProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { const body = new stream.PassThrough(); async function sendChunks () { await delay(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await delay(10); } body.push(null); } sendChunks(); return body; } // A promise that can be resolved externally. function defer (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as any).create({ sandbox: true }); }); after(() => (contents as any).destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); describe('protocol.registerStringProtocol', () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerBufferProtocol', () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerFileProtocol', () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it.skip('throws an error when custom headers are invalid', (done) => { registerFileProtocol(protocolName, (request, callback) => { expect(() => callback({ path: filePath, headers: { 'X-Great-Header': (42 as any) } })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string'); done(); }); ajax(protocolName + '://fake-host').catch(() => {}); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback(normalPath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerHttpProtocol', () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = 'http://127.0.0.1:' + port; registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); describe('protocol.registerStreamProtocol', () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = emittedOnce(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = emittedOnce(events, 'respond'); const hasClosedPromise = emittedOnce(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); server.listen(0, '127.0.0.1'); const port = (server.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}`; interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = defer(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const content = `<script>fetch("http://127.0.0.1:${port}")</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it.skip('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // FIXME: Figure out why this test is failing it.skip('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow = null as unknown as BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); });
closed
electron/electron
https://github.com/electron/electron
35,462
[Bug]: Electron crashes when loading <iframe> from custom URL protocol
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to load an iframe from a custom:// url protocol inside my main window. `<iframe src="custom://test.html">` ### Actual Behavior Application crashes when using custom:// url protocol. The protocol is registered with `protocol.registerFileProtocol()`. When loading the exact same file with the file:// protocol, everything is OK. ### Testcase Gist URL https://gist.github.com/75a34a8f7177e616146a8e5f1f4edddc ### Additional Information The same issue hase also been observed on Ubuntu 20.04
https://github.com/electron/electron/issues/35462
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2022-08-25T18:21:15Z
c++
2022-08-31T08:08:11Z
spec/fixtures/pages/iframe-protocol.html
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain } from 'electron/main'; import { AddressInfo } from 'net'; import * as ChildProcess from 'child_process'; import * as path from 'path'; import * as http from 'http'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as stream from 'stream'; import { EventEmitter } from 'events'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { WebmGenerator } from './video-helpers'; import { delay } from './spec-helpers'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerHttpProtocol = protocol.registerHttpProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { const body = new stream.PassThrough(); async function sendChunks () { await delay(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await delay(10); } body.push(null); } sendChunks(); return body; } // A promise that can be resolved externally. function defer (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as any).create({ sandbox: true }); }); after(() => (contents as any).destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); describe('protocol.registerStringProtocol', () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerBufferProtocol', () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerFileProtocol', () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it.skip('throws an error when custom headers are invalid', (done) => { registerFileProtocol(protocolName, (request, callback) => { expect(() => callback({ path: filePath, headers: { 'X-Great-Header': (42 as any) } })).to.throw(Error, 'Value of \'X-Great-Header\' header has to be a string'); done(); }); ajax(protocolName + '://fake-host').catch(() => {}); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback(normalPath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback(fakeFilePath)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.registerHttpProtocol', () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = 'http://127.0.0.1:' + port; registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); describe('protocol.registerStreamProtocol', () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = emittedOnce(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = emittedOnce(events, 'respond'); const hasClosedPromise = emittedOnce(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); server.listen(0, '127.0.0.1'); const port = (server.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}`; interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }, 300); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = defer(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const content = `<script>fetch("http://127.0.0.1:${port}")</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it.skip('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // FIXME: Figure out why this test is failing it.skip('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow = null as unknown as BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout(() => { (newContents as any).destroy(); }); } } }); });
closed
electron/electron
https://github.com/electron/electron
28,407
[Bug]: Crash when loading iframe with custom protocol from file://
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 12.0.2 "electron-packager": "^15.2.0", ### What operating system are you using? Windows ### Operating System Version Windows 10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should not crash ### Actual Behavior Electron crashes when adding iframe ### Testcase Gist URL _No response_ [app.zip](https://github.com/electron/electron/files/6211709/app.zip) I've the following component wich crashes electron: export class SimpleReportViewer extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.container = document.createElement('div'); this.shadowRoot.appendChild(this.container); } loadIframe() { if (this.isConnected) { this._iframe = document.createElement("iframe"); this._iframe.style.width = "100%"; this._iframe.style.height = "100%"; this._iframe.src = '/iframe.html'; this.container.appendChild(this._iframe); } } connectedCallback() { this.loadIframe(); } } customElements.define('simple-report-viewer', SimpleReportViewer);
https://github.com/electron/electron/issues/28407
https://github.com/electron/electron/pull/35485
bfced8cbfe6bad6d119ea9276d13aa67accc9c9a
e0fb5cbe1fd84d9651e6030ebab683dd9e4af42d
2021-03-26T12:16:37Z
c++
2022-08-31T08:08:11Z
spec/fixtures/pages/iframe-protocol.html
closed
electron/electron
https://github.com/electron/electron
35,471
[Bug]: Segfault when calling `screen.getCursorScreenPoint()` under Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v20.0.3 and v22.0.0-nightly.20220824 ### What operating system are you using? Other Linux, and Sway WM (1.7) ### Operating System Version ArchLinux, kernel 5.19.3 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Should provide a Point to the cursor position and not segfault. ### Actual Behavior Get a segmentation fault when calling `screen.getCursorScreenPoint();` under Wayland (sway 1.7). ### Testcase Gist URL https://gist.github.com/weedz/b8002775cd1a23c46d38b5f10de957e4 ### Additional Information Works fine under Xwayland. But will crash when launched with `--ozone-platform-hint=wayland`. Tested every version down to electron@16 (with `--enable-features=UseOzonePlatform --ozone-platform=wayland`: - Electron@16: "interface 'wl_output' has no event 4" and no window or other errors. - Electron v17-v22.0.0-nightly.20220824: "electron exited with signal SIGSEGV"
https://github.com/electron/electron/issues/35471
https://github.com/electron/electron/pull/35503
98c0fa1c8b4759eff243807b625094d5ef2840a8
2db0f7f8d44be93190323a94c4a1fc255251bfa5
2022-08-26T21:19:42Z
c++
2022-09-05T08:10:50Z
shell/browser/api/electron_api_screen.cc
// Copyright (c) 2013 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_screen.h" #include <string> #include "base/bind.h" #include "gin/dictionary.h" #include "gin/handle.h" #include "shell/browser/browser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/point.h" #if BUILDFLAG(IS_WIN) #include "ui/display/win/screen_win.h" #endif namespace electron::api { gin::WrapperInfo Screen::kWrapperInfo = {gin::kEmbedderNativeGin}; namespace { // Convert the changed_metrics bitmask to string array. std::vector<std::string> MetricsToArray(uint32_t metrics) { std::vector<std::string> array; if (metrics & display::DisplayObserver::DISPLAY_METRIC_BOUNDS) array.emplace_back("bounds"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_WORK_AREA) array.emplace_back("workArea"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR) array.emplace_back("scaleFactor"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION) array.emplace_back("rotation"); return array; } void DelayEmit(Screen* screen, base::StringPiece name, const display::Display& display) { screen->Emit(name, display); } void DelayEmitWithMetrics(Screen* screen, base::StringPiece name, const display::Display& display, const std::vector<std::string>& metrics) { screen->Emit(name, display, metrics); } } // namespace Screen::Screen(v8::Isolate* isolate, display::Screen* screen) : screen_(screen) { screen_->AddObserver(this); } Screen::~Screen() { screen_->RemoveObserver(this); } gfx::Point Screen::GetCursorScreenPoint() { return screen_->GetCursorScreenPoint(); } display::Display Screen::GetPrimaryDisplay() { return screen_->GetPrimaryDisplay(); } std::vector<display::Display> Screen::GetAllDisplays() { return screen_->GetAllDisplays(); } display::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { return screen_->GetDisplayNearestPoint(point); } display::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { return screen_->GetDisplayMatching(match_rect); } #if BUILDFLAG(IS_WIN) static gfx::Rect ScreenToDIPRect(electron::NativeWindow* window, const gfx::Rect& rect) { HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr; return display::win::ScreenWin::ScreenToDIPRect(hwnd, rect); } static gfx::Rect DIPToScreenRect(electron::NativeWindow* window, const gfx::Rect& rect) { HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr; return display::win::ScreenWin::DIPToScreenRect(hwnd, rect); } #endif void Screen::OnDisplayAdded(const display::Display& new_display) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmit, base::Unretained(this), "display-added", new_display)); } void Screen::OnDisplayRemoved(const display::Display& old_display) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmit, base::Unretained(this), "display-removed", old_display)); } void Screen::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmitWithMetrics, base::Unretained(this), "display-metrics-changed", display, MetricsToArray(changed_metrics))); } // static v8::Local<v8::Value> Screen::Create(gin_helper::ErrorThrower error_thrower) { if (!Browser::Get()->is_ready()) { error_thrower.ThrowError( "The 'screen' module can't be used before the app 'ready' event"); return v8::Null(error_thrower.isolate()); } display::Screen* screen = display::Screen::GetScreen(); if (!screen) { error_thrower.ThrowError("Failed to get screen information"); return v8::Null(error_thrower.isolate()); } return gin::CreateHandle(error_thrower.isolate(), new Screen(error_thrower.isolate(), screen)) .ToV8(); } gin::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Screen>::GetObjectTemplateBuilder( isolate) .SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint) .SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay) .SetMethod("getAllDisplays", &Screen::GetAllDisplays) .SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint) #if BUILDFLAG(IS_WIN) .SetMethod("screenToDipPoint", &display::win::ScreenWin::ScreenToDIPPoint) .SetMethod("dipToScreenPoint", &display::win::ScreenWin::DIPToScreenPoint) .SetMethod("screenToDipRect", &ScreenToDIPRect) .SetMethod("dipToScreenRect", &DIPToScreenRect) #endif .SetMethod("getDisplayMatching", &Screen::GetDisplayMatching); } const char* Screen::GetTypeName() { return "Screen"; } } // namespace electron::api namespace { using electron::api::Screen; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.SetMethod("createScreen", base::BindRepeating(&Screen::Create)); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_screen, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,471
[Bug]: Segfault when calling `screen.getCursorScreenPoint()` under Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v20.0.3 and v22.0.0-nightly.20220824 ### What operating system are you using? Other Linux, and Sway WM (1.7) ### Operating System Version ArchLinux, kernel 5.19.3 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Should provide a Point to the cursor position and not segfault. ### Actual Behavior Get a segmentation fault when calling `screen.getCursorScreenPoint();` under Wayland (sway 1.7). ### Testcase Gist URL https://gist.github.com/weedz/b8002775cd1a23c46d38b5f10de957e4 ### Additional Information Works fine under Xwayland. But will crash when launched with `--ozone-platform-hint=wayland`. Tested every version down to electron@16 (with `--enable-features=UseOzonePlatform --ozone-platform=wayland`: - Electron@16: "interface 'wl_output' has no event 4" and no window or other errors. - Electron v17-v22.0.0-nightly.20220824: "electron exited with signal SIGSEGV"
https://github.com/electron/electron/issues/35471
https://github.com/electron/electron/pull/35503
98c0fa1c8b4759eff243807b625094d5ef2840a8
2db0f7f8d44be93190323a94c4a1fc255251bfa5
2022-08-26T21:19:42Z
c++
2022-09-05T08:10:50Z
shell/browser/api/electron_api_screen.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_ #include <vector> #include "gin/wrappable.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/common/gin_helper/error_thrower.h" #include "ui/display/display_observer.h" #include "ui/display/screen.h" namespace gfx { class Point; class Rect; class Screen; } // namespace gfx namespace electron::api { class Screen : public gin::Wrappable<Screen>, public gin_helper::EventEmitterMixin<Screen>, public display::DisplayObserver { public: static v8::Local<v8::Value> Create(gin_helper::ErrorThrower error_thrower); static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; const char* GetTypeName() override; // disable copy Screen(const Screen&) = delete; Screen& operator=(const Screen&) = delete; protected: Screen(v8::Isolate* isolate, display::Screen* screen); ~Screen() override; gfx::Point GetCursorScreenPoint(); display::Display GetPrimaryDisplay(); std::vector<display::Display> GetAllDisplays(); display::Display GetDisplayNearestPoint(const gfx::Point& point); display::Display GetDisplayMatching(const gfx::Rect& match_rect); // display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override; void OnDisplayRemoved(const display::Display& old_display) override; void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: display::Screen* screen_; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_
closed
electron/electron
https://github.com/electron/electron
35,471
[Bug]: Segfault when calling `screen.getCursorScreenPoint()` under Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v20.0.3 and v22.0.0-nightly.20220824 ### What operating system are you using? Other Linux, and Sway WM (1.7) ### Operating System Version ArchLinux, kernel 5.19.3 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Should provide a Point to the cursor position and not segfault. ### Actual Behavior Get a segmentation fault when calling `screen.getCursorScreenPoint();` under Wayland (sway 1.7). ### Testcase Gist URL https://gist.github.com/weedz/b8002775cd1a23c46d38b5f10de957e4 ### Additional Information Works fine under Xwayland. But will crash when launched with `--ozone-platform-hint=wayland`. Tested every version down to electron@16 (with `--enable-features=UseOzonePlatform --ozone-platform=wayland`: - Electron@16: "interface 'wl_output' has no event 4" and no window or other errors. - Electron v17-v22.0.0-nightly.20220824: "electron exited with signal SIGSEGV"
https://github.com/electron/electron/issues/35471
https://github.com/electron/electron/pull/35503
98c0fa1c8b4759eff243807b625094d5ef2840a8
2db0f7f8d44be93190323a94c4a1fc255251bfa5
2022-08-26T21:19:42Z
c++
2022-09-05T08:10:50Z
shell/browser/api/electron_api_screen.cc
// Copyright (c) 2013 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_screen.h" #include <string> #include "base/bind.h" #include "gin/dictionary.h" #include "gin/handle.h" #include "shell/browser/browser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/native_window_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/geometry/point.h" #if BUILDFLAG(IS_WIN) #include "ui/display/win/screen_win.h" #endif namespace electron::api { gin::WrapperInfo Screen::kWrapperInfo = {gin::kEmbedderNativeGin}; namespace { // Convert the changed_metrics bitmask to string array. std::vector<std::string> MetricsToArray(uint32_t metrics) { std::vector<std::string> array; if (metrics & display::DisplayObserver::DISPLAY_METRIC_BOUNDS) array.emplace_back("bounds"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_WORK_AREA) array.emplace_back("workArea"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_DEVICE_SCALE_FACTOR) array.emplace_back("scaleFactor"); if (metrics & display::DisplayObserver::DISPLAY_METRIC_ROTATION) array.emplace_back("rotation"); return array; } void DelayEmit(Screen* screen, base::StringPiece name, const display::Display& display) { screen->Emit(name, display); } void DelayEmitWithMetrics(Screen* screen, base::StringPiece name, const display::Display& display, const std::vector<std::string>& metrics) { screen->Emit(name, display, metrics); } } // namespace Screen::Screen(v8::Isolate* isolate, display::Screen* screen) : screen_(screen) { screen_->AddObserver(this); } Screen::~Screen() { screen_->RemoveObserver(this); } gfx::Point Screen::GetCursorScreenPoint() { return screen_->GetCursorScreenPoint(); } display::Display Screen::GetPrimaryDisplay() { return screen_->GetPrimaryDisplay(); } std::vector<display::Display> Screen::GetAllDisplays() { return screen_->GetAllDisplays(); } display::Display Screen::GetDisplayNearestPoint(const gfx::Point& point) { return screen_->GetDisplayNearestPoint(point); } display::Display Screen::GetDisplayMatching(const gfx::Rect& match_rect) { return screen_->GetDisplayMatching(match_rect); } #if BUILDFLAG(IS_WIN) static gfx::Rect ScreenToDIPRect(electron::NativeWindow* window, const gfx::Rect& rect) { HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr; return display::win::ScreenWin::ScreenToDIPRect(hwnd, rect); } static gfx::Rect DIPToScreenRect(electron::NativeWindow* window, const gfx::Rect& rect) { HWND hwnd = window ? window->GetAcceleratedWidget() : nullptr; return display::win::ScreenWin::DIPToScreenRect(hwnd, rect); } #endif void Screen::OnDisplayAdded(const display::Display& new_display) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmit, base::Unretained(this), "display-added", new_display)); } void Screen::OnDisplayRemoved(const display::Display& old_display) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmit, base::Unretained(this), "display-removed", old_display)); } void Screen::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::BindOnce(&DelayEmitWithMetrics, base::Unretained(this), "display-metrics-changed", display, MetricsToArray(changed_metrics))); } // static v8::Local<v8::Value> Screen::Create(gin_helper::ErrorThrower error_thrower) { if (!Browser::Get()->is_ready()) { error_thrower.ThrowError( "The 'screen' module can't be used before the app 'ready' event"); return v8::Null(error_thrower.isolate()); } display::Screen* screen = display::Screen::GetScreen(); if (!screen) { error_thrower.ThrowError("Failed to get screen information"); return v8::Null(error_thrower.isolate()); } return gin::CreateHandle(error_thrower.isolate(), new Screen(error_thrower.isolate(), screen)) .ToV8(); } gin::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Screen>::GetObjectTemplateBuilder( isolate) .SetMethod("getCursorScreenPoint", &Screen::GetCursorScreenPoint) .SetMethod("getPrimaryDisplay", &Screen::GetPrimaryDisplay) .SetMethod("getAllDisplays", &Screen::GetAllDisplays) .SetMethod("getDisplayNearestPoint", &Screen::GetDisplayNearestPoint) #if BUILDFLAG(IS_WIN) .SetMethod("screenToDipPoint", &display::win::ScreenWin::ScreenToDIPPoint) .SetMethod("dipToScreenPoint", &display::win::ScreenWin::DIPToScreenPoint) .SetMethod("screenToDipRect", &ScreenToDIPRect) .SetMethod("dipToScreenRect", &DIPToScreenRect) #endif .SetMethod("getDisplayMatching", &Screen::GetDisplayMatching); } const char* Screen::GetTypeName() { return "Screen"; } } // namespace electron::api namespace { using electron::api::Screen; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.SetMethod("createScreen", base::BindRepeating(&Screen::Create)); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_screen, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,471
[Bug]: Segfault when calling `screen.getCursorScreenPoint()` under Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v20.0.3 and v22.0.0-nightly.20220824 ### What operating system are you using? Other Linux, and Sway WM (1.7) ### Operating System Version ArchLinux, kernel 5.19.3 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Should provide a Point to the cursor position and not segfault. ### Actual Behavior Get a segmentation fault when calling `screen.getCursorScreenPoint();` under Wayland (sway 1.7). ### Testcase Gist URL https://gist.github.com/weedz/b8002775cd1a23c46d38b5f10de957e4 ### Additional Information Works fine under Xwayland. But will crash when launched with `--ozone-platform-hint=wayland`. Tested every version down to electron@16 (with `--enable-features=UseOzonePlatform --ozone-platform=wayland`: - Electron@16: "interface 'wl_output' has no event 4" and no window or other errors. - Electron v17-v22.0.0-nightly.20220824: "electron exited with signal SIGSEGV"
https://github.com/electron/electron/issues/35471
https://github.com/electron/electron/pull/35503
98c0fa1c8b4759eff243807b625094d5ef2840a8
2db0f7f8d44be93190323a94c4a1fc255251bfa5
2022-08-26T21:19:42Z
c++
2022-09-05T08:10:50Z
shell/browser/api/electron_api_screen.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_ #include <vector> #include "gin/wrappable.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/common/gin_helper/error_thrower.h" #include "ui/display/display_observer.h" #include "ui/display/screen.h" namespace gfx { class Point; class Rect; class Screen; } // namespace gfx namespace electron::api { class Screen : public gin::Wrappable<Screen>, public gin_helper::EventEmitterMixin<Screen>, public display::DisplayObserver { public: static v8::Local<v8::Value> Create(gin_helper::ErrorThrower error_thrower); static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; const char* GetTypeName() override; // disable copy Screen(const Screen&) = delete; Screen& operator=(const Screen&) = delete; protected: Screen(v8::Isolate* isolate, display::Screen* screen); ~Screen() override; gfx::Point GetCursorScreenPoint(); display::Display GetPrimaryDisplay(); std::vector<display::Display> GetAllDisplays(); display::Display GetDisplayNearestPoint(const gfx::Point& point); display::Display GetDisplayMatching(const gfx::Rect& match_rect); // display::DisplayObserver: void OnDisplayAdded(const display::Display& new_display) override; void OnDisplayRemoved(const display::Display& old_display) override; void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: display::Screen* screen_; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SCREEN_H_
closed
electron/electron
https://github.com/electron/electron
35,157
[Docs] Wrong usage of `ipcMain.handle` in `/tutorial-preload`
https://github.com/electron/electron/blob/b67c69d741c648569d86c5a7846f2559219f9b14/docs/tutorial/tutorial-3-preload.md?plain=1#L198 1. Follow tutorial on a Mac 2. close only window 3. open another window 4. notice error It should not be called for every window but just once inside main.js <img width="283" alt="Screen Shot 2022-08-01 at 13 48 44" src="https://user-images.githubusercontent.com/163636/182133832-033f31ee-423f-4ab9-95d7-8cbbb5f7b1da.png">
https://github.com/electron/electron/issues/35157
https://github.com/electron/electron/pull/35479
87145c393c08203e6e18f0615a13baff59fb3e30
c16baa063a404c9afefe452ef88a28cfa7cc2241
2022-08-01T10:56:00Z
c++
2022-09-07T13:37:29Z
docs/tutorial/tutorial-3-preload.md
--- title: 'Using Preload Scripts' description: 'This guide will step you through the process of creating a barebones Hello World app in Electron, similar to electron/electron-quick-start.' slug: tutorial-preload hide_title: false --- :::info Follow along the tutorial This is **part 3** of the Electron tutorial. 1. [Prerequisites][prerequisites] 1. [Building your First App][building your first app] 1. **[Using Preload Scripts][preload]** 1. [Adding Features][features] 1. [Packaging Your Application][packaging] 1. [Publishing and Updating][updates] ::: ## Learning goals In this part of the tutorial, you will learn what a preload script is and how to use one to securely expose privileged APIs into the renderer process. You will also learn how to communicate between main and renderer processes with Electron's inter-process communication (IPC) modules. ## What is a preload script? Electron's main process is a Node.js environment that has full operating system access. On top of [Electron modules][modules], you can also access [Node.js built-ins][node-api], as well as any packages installed via npm. On the other hand, renderer processes run web pages and do not run Node.js by default for security reasons. To bridge Electron's different process types together, we will need to use a special script called a **preload**. ## Augmenting the renderer with a preload script A BrowserWindow's preload script runs in a context that has access to both the HTML DOM and a Node.js environment. Preload scripts are injected before a web page loads in the renderer, similar to a Chrome extension's [content scripts][content-script]. To add features to your renderer that require privileged access, you can define [global] objects through the [contextBridge][contextbridge] API. To demonstrate this concept, you will create a preload script that exposes your app's versions of Chrome, Node, and Electron into the renderer. Add a new `preload.js` script that exposes selected properties of Electron's `process.versions` object to the renderer process in a `versions` global variable. ```js title="preload.js" const { contextBridge } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, // we can also expose variables, not just functions }) ``` To attach this script to your renderer process, pass its path to the `webPreferences.preload` option in the BrowserWindow constructor: ```js {8-10} title="main.js" const { app, BrowserWindow } = require('electron') const path = require('path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() }) ``` :::info There are two Node.js concepts that are used here: - The [`__dirname`][dirname] string points to the path of the currently executing script (in this case, your project's root folder). - The [`path.join`][path-join] API joins multiple path segments together, creating a combined path string that works across all platforms. ::: At this point, the renderer has access to the `versions` global, so let's display that information in the window. This variable can be accessed via `window.versions` or simply `versions`. Create a `renderer.js` script that uses the [`document.getElementById`] DOM API to replace the displayed text for the HTML element with `info` as its `id` property. ```js title="renderer.js" const information = document.getElementById('info') information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})` ``` Then, modify your `index.html` by adding a new element with `info` as its `id` property, and attach your `renderer.js` script: ```html {18,20} title="index.html" <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <title>Hello from Electron renderer!</title> </head> <body> <h1>Hello from Electron renderer!</h1> <p>👋</p> <p id="info"></p> </body> <script src="./renderer.js"></script> </html> ``` After following the above steps, your app should look something like this: ![Electron app showing This app is using Chrome (v102.0.5005.63), Node.js (v16.14.2), and Electron (v19.0.3)](../images/preload-example.png) And the code should look like this: ```fiddle docs/fiddles/tutorial-preload ``` ## Communicating between processes As we have mentioned above, Electron's main and renderer process have distinct responsibilities and are not interchangeable. This means it is not possible to access the Node.js APIs directly from the renderer process, nor the HTML Document Object Model (DOM) from the main process. The solution for this problem is to use Electron's `ipcMain` and `ipcRenderer` modules for inter-process communication (IPC). To send a message from your web page to the main process, you can set up a main process handler with `ipcMain.handle` and then expose a function that calls `ipcRenderer.invoke` to trigger the handler in your preload script. To illustrate, we will add a global function to the renderer called `ping()` that will return a string from the main process. First, set up the `invoke` call in your preload script: ```js {1,7} title="preload.js" const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, ping: () => ipcRenderer.invoke('ping'), // we can also expose variables, not just functions }) ``` :::caution IPC security Notice how we wrap the `ipcRenderer.invoke('ping')` call in a helper function rather than expose the `ipcRenderer` module directly via context bridge. You **never** want to directly expose the entire `ipcRenderer` module via preload. This would give your renderer the ability to send arbitrary IPC messages to the main process, which becomes a powerful attack vector for malicious code. ::: Then, set up your `handle` listener in the main process. We do this _before_ loading the HTML file so that the handler is guaranteed to be ready before you send out the `invoke` call from the renderer. ```js {1,11} title="main.js" const { ipcMain } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) ipcMain.handle('ping', () => 'pong') win.loadFile('index.html') } ``` Once you have the sender and receiver set up, you can now send messages from the renderer to the main process through the `'ping'` channel you just defined. ```js title='renderer.js' const func = async () => { const response = await window.versions.ping() console.log(response) // prints out 'pong' } func() ``` :::info For more in-depth explanations on using the `ipcRenderer` and `ipcMain` modules, check out the full [Inter-Process Communication][ipc] guide. ::: ## Summary A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node.js environment, and is often used to expose privileged APIs to the renderer via the `contextBridge` API. Because the main and renderer processes have very different responsibilities, Electron apps often use the preload script to set up inter-process communication (IPC) interfaces to pass arbitrary messages between the two kinds of processes. In the next part of the tutorial, we will be showing you resources on adding more functionality to your app, then teaching you distributing your app to users. <!-- Links --> [advanced-installation]: ./installation.md [application debugging]: ./application-debugging.md [app]: ../api/app.md [app-ready]: ../api/app.md#event-ready [app-when-ready]: ../api/app.md#appwhenready [browser-window]: ../api/browser-window.md [commonjs]: https://nodejs.org/docs/latest/api/modules.html#modules_modules_commonjs_modules [compound task]: https://code.visualstudio.com/Docs/editor/tasks#_compound-tasks [content-script]: https://developer.chrome.com/docs/extensions/mv3/content_scripts/ [contextbridge]: ../api/context-bridge.md [context-isolation]: ./context-isolation.md [`document.getelementbyid`]: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById [devtools-extension]: ./devtools-extension.md [dirname]: https://nodejs.org/api/modules.html#modules_dirname [global]: https://developer.mozilla.org/en-US/docs/Glossary/Global_object [ipc]: ./ipc.md [mdn-csp]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP [modules]: ../api/app.md [node-api]: https://nodejs.org/dist/latest/docs/api/ [package-json-main]: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main [package-scripts]: https://docs.npmjs.com/cli/v7/using-npm/scripts [path-join]: https://nodejs.org/api/path.html#path_path_join_paths [process-model]: ./process-model.md [react]: https://reactjs.org [sandbox]: ./sandbox.md [webpack]: https://webpack.js.org <!-- Tutorial links --> [prerequisites]: tutorial-1-prerequisites.md [building your first app]: tutorial-2-first-app.md [preload]: tutorial-3-preload.md [features]: tutorial-4-adding-features.md [packaging]: tutorial-5-packaging.md [updates]: tutorial-6-publishing-updating.md
closed
electron/electron
https://github.com/electron/electron
35,157
[Docs] Wrong usage of `ipcMain.handle` in `/tutorial-preload`
https://github.com/electron/electron/blob/b67c69d741c648569d86c5a7846f2559219f9b14/docs/tutorial/tutorial-3-preload.md?plain=1#L198 1. Follow tutorial on a Mac 2. close only window 3. open another window 4. notice error It should not be called for every window but just once inside main.js <img width="283" alt="Screen Shot 2022-08-01 at 13 48 44" src="https://user-images.githubusercontent.com/163636/182133832-033f31ee-423f-4ab9-95d7-8cbbb5f7b1da.png">
https://github.com/electron/electron/issues/35157
https://github.com/electron/electron/pull/35479
87145c393c08203e6e18f0615a13baff59fb3e30
c16baa063a404c9afefe452ef88a28cfa7cc2241
2022-08-01T10:56:00Z
c++
2022-09-07T13:37:29Z
docs/tutorial/tutorial-3-preload.md
--- title: 'Using Preload Scripts' description: 'This guide will step you through the process of creating a barebones Hello World app in Electron, similar to electron/electron-quick-start.' slug: tutorial-preload hide_title: false --- :::info Follow along the tutorial This is **part 3** of the Electron tutorial. 1. [Prerequisites][prerequisites] 1. [Building your First App][building your first app] 1. **[Using Preload Scripts][preload]** 1. [Adding Features][features] 1. [Packaging Your Application][packaging] 1. [Publishing and Updating][updates] ::: ## Learning goals In this part of the tutorial, you will learn what a preload script is and how to use one to securely expose privileged APIs into the renderer process. You will also learn how to communicate between main and renderer processes with Electron's inter-process communication (IPC) modules. ## What is a preload script? Electron's main process is a Node.js environment that has full operating system access. On top of [Electron modules][modules], you can also access [Node.js built-ins][node-api], as well as any packages installed via npm. On the other hand, renderer processes run web pages and do not run Node.js by default for security reasons. To bridge Electron's different process types together, we will need to use a special script called a **preload**. ## Augmenting the renderer with a preload script A BrowserWindow's preload script runs in a context that has access to both the HTML DOM and a Node.js environment. Preload scripts are injected before a web page loads in the renderer, similar to a Chrome extension's [content scripts][content-script]. To add features to your renderer that require privileged access, you can define [global] objects through the [contextBridge][contextbridge] API. To demonstrate this concept, you will create a preload script that exposes your app's versions of Chrome, Node, and Electron into the renderer. Add a new `preload.js` script that exposes selected properties of Electron's `process.versions` object to the renderer process in a `versions` global variable. ```js title="preload.js" const { contextBridge } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, // we can also expose variables, not just functions }) ``` To attach this script to your renderer process, pass its path to the `webPreferences.preload` option in the BrowserWindow constructor: ```js {8-10} title="main.js" const { app, BrowserWindow } = require('electron') const path = require('path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) win.loadFile('index.html') } app.whenReady().then(() => { createWindow() }) ``` :::info There are two Node.js concepts that are used here: - The [`__dirname`][dirname] string points to the path of the currently executing script (in this case, your project's root folder). - The [`path.join`][path-join] API joins multiple path segments together, creating a combined path string that works across all platforms. ::: At this point, the renderer has access to the `versions` global, so let's display that information in the window. This variable can be accessed via `window.versions` or simply `versions`. Create a `renderer.js` script that uses the [`document.getElementById`] DOM API to replace the displayed text for the HTML element with `info` as its `id` property. ```js title="renderer.js" const information = document.getElementById('info') information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})` ``` Then, modify your `index.html` by adding a new element with `info` as its `id` property, and attach your `renderer.js` script: ```html {18,20} title="index.html" <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <title>Hello from Electron renderer!</title> </head> <body> <h1>Hello from Electron renderer!</h1> <p>👋</p> <p id="info"></p> </body> <script src="./renderer.js"></script> </html> ``` After following the above steps, your app should look something like this: ![Electron app showing This app is using Chrome (v102.0.5005.63), Node.js (v16.14.2), and Electron (v19.0.3)](../images/preload-example.png) And the code should look like this: ```fiddle docs/fiddles/tutorial-preload ``` ## Communicating between processes As we have mentioned above, Electron's main and renderer process have distinct responsibilities and are not interchangeable. This means it is not possible to access the Node.js APIs directly from the renderer process, nor the HTML Document Object Model (DOM) from the main process. The solution for this problem is to use Electron's `ipcMain` and `ipcRenderer` modules for inter-process communication (IPC). To send a message from your web page to the main process, you can set up a main process handler with `ipcMain.handle` and then expose a function that calls `ipcRenderer.invoke` to trigger the handler in your preload script. To illustrate, we will add a global function to the renderer called `ping()` that will return a string from the main process. First, set up the `invoke` call in your preload script: ```js {1,7} title="preload.js" const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, ping: () => ipcRenderer.invoke('ping'), // we can also expose variables, not just functions }) ``` :::caution IPC security Notice how we wrap the `ipcRenderer.invoke('ping')` call in a helper function rather than expose the `ipcRenderer` module directly via context bridge. You **never** want to directly expose the entire `ipcRenderer` module via preload. This would give your renderer the ability to send arbitrary IPC messages to the main process, which becomes a powerful attack vector for malicious code. ::: Then, set up your `handle` listener in the main process. We do this _before_ loading the HTML file so that the handler is guaranteed to be ready before you send out the `invoke` call from the renderer. ```js {1,11} title="main.js" const { ipcMain } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) ipcMain.handle('ping', () => 'pong') win.loadFile('index.html') } ``` Once you have the sender and receiver set up, you can now send messages from the renderer to the main process through the `'ping'` channel you just defined. ```js title='renderer.js' const func = async () => { const response = await window.versions.ping() console.log(response) // prints out 'pong' } func() ``` :::info For more in-depth explanations on using the `ipcRenderer` and `ipcMain` modules, check out the full [Inter-Process Communication][ipc] guide. ::: ## Summary A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node.js environment, and is often used to expose privileged APIs to the renderer via the `contextBridge` API. Because the main and renderer processes have very different responsibilities, Electron apps often use the preload script to set up inter-process communication (IPC) interfaces to pass arbitrary messages between the two kinds of processes. In the next part of the tutorial, we will be showing you resources on adding more functionality to your app, then teaching you distributing your app to users. <!-- Links --> [advanced-installation]: ./installation.md [application debugging]: ./application-debugging.md [app]: ../api/app.md [app-ready]: ../api/app.md#event-ready [app-when-ready]: ../api/app.md#appwhenready [browser-window]: ../api/browser-window.md [commonjs]: https://nodejs.org/docs/latest/api/modules.html#modules_modules_commonjs_modules [compound task]: https://code.visualstudio.com/Docs/editor/tasks#_compound-tasks [content-script]: https://developer.chrome.com/docs/extensions/mv3/content_scripts/ [contextbridge]: ../api/context-bridge.md [context-isolation]: ./context-isolation.md [`document.getelementbyid`]: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById [devtools-extension]: ./devtools-extension.md [dirname]: https://nodejs.org/api/modules.html#modules_dirname [global]: https://developer.mozilla.org/en-US/docs/Glossary/Global_object [ipc]: ./ipc.md [mdn-csp]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP [modules]: ../api/app.md [node-api]: https://nodejs.org/dist/latest/docs/api/ [package-json-main]: https://docs.npmjs.com/cli/v7/configuring-npm/package-json#main [package-scripts]: https://docs.npmjs.com/cli/v7/using-npm/scripts [path-join]: https://nodejs.org/api/path.html#path_path_join_paths [process-model]: ./process-model.md [react]: https://reactjs.org [sandbox]: ./sandbox.md [webpack]: https://webpack.js.org <!-- Tutorial links --> [prerequisites]: tutorial-1-prerequisites.md [building your first app]: tutorial-2-first-app.md [preload]: tutorial-3-preload.md [features]: tutorial-4-adding-features.md [packaging]: tutorial-5-packaging.md [updates]: tutorial-6-publishing-updating.md
closed
electron/electron
https://github.com/electron/electron
34,398
[Bug]: session.getBlobData never resolves with blob sizes > 65536
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 (21E258) ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When running `session.getBlobData` on a blob UUID from an `onBeforeRequest` handler, I expect the resulting promise to resolve successfully to a buffer when the blob size is <<< RAM size. According to https://source.chromium.org/chromium/chromium/src/+/main:storage/browser/blob/blob_memory_controller.cc?q=CalculateBlobStorageLimitsImpl&ss=chromium, a blob of size 65537 should be handled correctly. ### Actual Behavior When calling `session.getBlobData` on a blob with size > 65536, the resulting promise never resolves. ### Testcase Gist URL https://gist.github.com/b3b9955084b145c77987e4dbc6c81078 ### Additional Information This issue appears to be a possible duplicate of https://github.com/electron/electron/issues/33081, though the other issue includes very little additional information, so I have filed a separate issue to be safe. I did a bit of digging through the Electron glue source, and I found the following: https://github.com/electron/electron/blob/61374019c03ab1af8584550277318ba7c2adb0ca/shell/browser/api/electron_api_session.cc#L725-L735 https://github.com/electron/electron/blob/c4ea33d1bf6faf8ca685e67e63b197d89efa9870/shell/browser/api/electron_api_data_pipe_holder.h#L33-L35 I suspect that this is related.
https://github.com/electron/electron/issues/34398
https://github.com/electron/electron/pull/35277
3a6d6ff0083408588af10a8931f881d7ee134622
e3efa16415ac090b38bd87d6b509ccecc90cefa0
2022-06-01T00:55:38Z
c++
2022-09-07T21:47:06Z
shell/browser/api/electron_api_data_pipe_holder.cc
// Copyright (c) 2019 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_data_pipe_holder.h" #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/base/net_errors.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/key_weak_map.h" #include "shell/common/node_includes.h" namespace electron::api { namespace { // Incremental ID. int g_next_id = 0; // Map that manages all the DataPipeHolder objects. KeyWeakMap<std::string>& AllDataPipeHolders() { static base::NoDestructor<KeyWeakMap<std::string>> weak_map; return *weak_map.get(); } // Utility class to read from data pipe. class DataPipeReader { public: DataPipeReader(gin_helper::Promise<v8::Local<v8::Value>> promise, mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter) : promise_(std::move(promise)), data_pipe_getter_(std::move(data_pipe_getter)), handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()) { // Get a new data pipe and start. mojo::ScopedDataPipeProducerHandle producer_handle; CHECK_EQ(mojo::CreateDataPipe(nullptr, producer_handle, data_pipe_), MOJO_RESULT_OK); data_pipe_getter_->Read(std::move(producer_handle), base::BindOnce(&DataPipeReader::ReadCallback, weak_factory_.GetWeakPtr())); handle_watcher_.Watch(data_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, base::BindRepeating(&DataPipeReader::OnHandleReadable, weak_factory_.GetWeakPtr())); } ~DataPipeReader() = default; // disable copy DataPipeReader(const DataPipeReader&) = delete; DataPipeReader& operator=(const DataPipeReader&) = delete; private: // Callback invoked by DataPipeGetter::Read. void ReadCallback(int32_t status, uint64_t size) { if (status != net::OK) { OnFailure(); return; } buffer_.resize(size); head_ = &buffer_.front(); remaining_size_ = size; handle_watcher_.ArmOrNotify(); } // Called by |handle_watcher_| when data is available or the pipe was closed, // and there's a pending Read() call. void OnHandleReadable(MojoResult result) { if (result != MOJO_RESULT_OK) { OnFailure(); return; } // Read. uint32_t length = remaining_size_; result = data_pipe_->ReadData(head_, &length, MOJO_READ_DATA_FLAG_NONE); if (result == MOJO_RESULT_OK) { // success remaining_size_ -= length; head_ += length; if (remaining_size_ == 0) OnSuccess(); } else if (result == MOJO_RESULT_SHOULD_WAIT) { // IO pending handle_watcher_.ArmOrNotify(); } else { // error OnFailure(); } } void OnFailure() { promise_.RejectWithErrorMessage("Could not get blob data"); delete this; } void OnSuccess() { // Copy the buffer to JS. // TODO(nornagon): make this zero-copy by allocating the array buffer // inside the sandbox v8::HandleScope handle_scope(promise_.isolate()); v8::Local<v8::Value> buffer = node::Buffer::Copy(promise_.isolate(), &buffer_.front(), buffer_.size()) .ToLocalChecked(); promise_.Resolve(buffer); // Destroy data pipe. handle_watcher_.Cancel(); delete this; } gin_helper::Promise<v8::Local<v8::Value>> promise_; mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter_; mojo::ScopedDataPipeConsumerHandle data_pipe_; mojo::SimpleWatcher handle_watcher_; // Stores read data. std::vector<char> buffer_; // The head of buffer. char* head_ = nullptr; // Remaining data to read. uint64_t remaining_size_ = 0; base::WeakPtrFactory<DataPipeReader> weak_factory_{this}; }; } // namespace gin::WrapperInfo DataPipeHolder::kWrapperInfo = {gin::kEmbedderNativeGin}; DataPipeHolder::DataPipeHolder(const network::DataElement& element) : id_(base::NumberToString(++g_next_id)) { data_pipe_.Bind( element.As<network::DataElementDataPipe>().CloneDataPipeGetter()); } DataPipeHolder::~DataPipeHolder() = default; v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) { gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!data_pipe_) { promise.RejectWithErrorMessage("Could not get blob data"); return handle; } new DataPipeReader(std::move(promise), std::move(data_pipe_)); return handle; } // static gin::Handle<DataPipeHolder> DataPipeHolder::Create( v8::Isolate* isolate, const network::DataElement& element) { auto handle = gin::CreateHandle(isolate, new DataPipeHolder(element)); AllDataPipeHolders().Set(isolate, handle->id(), handle->GetWrapper(isolate).ToLocalChecked()); return handle; } // static gin::Handle<DataPipeHolder> DataPipeHolder::From(v8::Isolate* isolate, const std::string& id) { v8::MaybeLocal<v8::Object> object = AllDataPipeHolders().Get(isolate, id); if (!object.IsEmpty()) { gin::Handle<DataPipeHolder> handle; if (gin::ConvertFromV8(isolate, object.ToLocalChecked(), &handle)) return handle; } return gin::Handle<DataPipeHolder>(); } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
34,398
[Bug]: session.getBlobData never resolves with blob sizes > 65536
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 (21E258) ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When running `session.getBlobData` on a blob UUID from an `onBeforeRequest` handler, I expect the resulting promise to resolve successfully to a buffer when the blob size is <<< RAM size. According to https://source.chromium.org/chromium/chromium/src/+/main:storage/browser/blob/blob_memory_controller.cc?q=CalculateBlobStorageLimitsImpl&ss=chromium, a blob of size 65537 should be handled correctly. ### Actual Behavior When calling `session.getBlobData` on a blob with size > 65536, the resulting promise never resolves. ### Testcase Gist URL https://gist.github.com/b3b9955084b145c77987e4dbc6c81078 ### Additional Information This issue appears to be a possible duplicate of https://github.com/electron/electron/issues/33081, though the other issue includes very little additional information, so I have filed a separate issue to be safe. I did a bit of digging through the Electron glue source, and I found the following: https://github.com/electron/electron/blob/61374019c03ab1af8584550277318ba7c2adb0ca/shell/browser/api/electron_api_session.cc#L725-L735 https://github.com/electron/electron/blob/c4ea33d1bf6faf8ca685e67e63b197d89efa9870/shell/browser/api/electron_api_data_pipe_holder.h#L33-L35 I suspect that this is related.
https://github.com/electron/electron/issues/34398
https://github.com/electron/electron/pull/35277
3a6d6ff0083408588af10a8931f881d7ee134622
e3efa16415ac090b38bd87d6b509ccecc90cefa0
2022-06-01T00:55:38Z
c++
2022-09-07T21:47:06Z
spec/api-session-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as https from 'https'; import * as path from 'path'; import * as fs from 'fs'; import * as ChildProcess from 'child_process'; import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main'; import * as send from 'send'; import * as auth from 'basic-auth'; import { closeAllWindows } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { defer, delay } from './spec-helpers'; import { AddressInfo } from 'net'; /* The whole session API doesn't use standard callbacks */ /* eslint-disable standard/no-callback-literal */ describe('session module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const url = 'http://127.0.0.1'; describe('session.defaultSession', () => { it('returns the default session', () => { expect(session.defaultSession).to.equal(session.fromPartition('')); }); }); describe('session.fromPartition(partition, options)', () => { it('returns existing session with same partition', () => { expect(session.fromPartition('test')).to.equal(session.fromPartition('test')); }); }); describe('ses.cookies', () => { const name = '0'; const value = '0'; afterEach(closeAllWindows); // Clear cookie of defaultSession after each test. afterEach(async () => { const { cookies } = session.defaultSession; const cs = await cookies.get({ url }); for (const c of cs) { await cookies.remove(url, c.name); } }); it('should get cookies', async () => { const server = http.createServer((req, res) => { res.setHeader('Set-Cookie', [`${name}=${value}`]); res.end('finished'); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const { port } = server.address() as AddressInfo; const w = new BrowserWindow({ show: false }); await w.loadURL(`${url}:${port}`); const list = await w.webContents.session.cookies.get({ url }); const cookie = list.find(cookie => cookie.name === name); expect(cookie).to.exist.and.to.have.property('value', value); }); it('sets cookies', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.equal(name); expect(c.value).to.equal(value); expect(c.session).to.equal(false); }); it('sets session cookies', async () => { const { cookies } = session.defaultSession; const name = '2'; const value = '1'; await cookies.set({ url, name, value }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.equal(name); expect(c.value).to.equal(value); expect(c.session).to.equal(true); }); it('sets cookies without name', async () => { const { cookies } = session.defaultSession; const value = '3'; await cookies.set({ url, value }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.be.empty(); expect(c.value).to.equal(value); }); for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) { it(`sets cookies with samesite=${sameSite}`, async () => { const { cookies } = session.defaultSession; const value = 'hithere'; await cookies.set({ url, value, sameSite }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.be.empty(); expect(c.value).to.equal(value); expect(c.sameSite).to.equal(sameSite); }); } it('fails to set cookies with samesite=garbage', async () => { const { cookies } = session.defaultSession; const value = 'hithere'; await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value'); }); it('gets cookies without url', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const cs = await cookies.get({ domain: '127.0.0.1' }); expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); }); it('yields an error when setting a cookie with missing required fields', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: '', name, value }) ).to.eventually.be.rejectedWith('Failed to get cookie domain'); }); it('yields an error when setting a cookie with an invalid URL', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: 'asdf', name, value }) ).to.eventually.be.rejectedWith('Failed to get cookie domain'); }); it('should overwrite previous cookies', async () => { const { cookies } = session.defaultSession; const name = 'DidOverwrite'; for (const value of ['No', 'Yes']) { await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const list = await cookies.get({ url }); expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true); } }); it('should remove cookies', async () => { const { cookies } = session.defaultSession; const name = '2'; const value = '2'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); await cookies.remove(url, name); const list = await cookies.get({ url }); expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false); }); it.skip('should set cookie for standard scheme', async () => { const { cookies } = session.defaultSession; const domain = 'fake-host'; const url = `${standardScheme}://${domain}`; const name = 'custom'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const list = await cookies.get({ url }); expect(list).to.have.lengthOf(1); expect(list[0]).to.have.property('name', name); expect(list[0]).to.have.property('value', value); expect(list[0]).to.have.property('domain', domain); }); it('emits a changed event when a cookie is added or removed', async () => { const { cookies } = session.fromPartition('cookies-changed'); const name = 'foo'; const value = 'bar'; const a = emittedOnce(cookies, 'changed'); await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const [, setEventCookie, setEventCause, setEventRemoved] = await a; const b = emittedOnce(cookies, 'changed'); await cookies.remove(url, name); const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b; expect(setEventCookie.name).to.equal(name); expect(setEventCookie.value).to.equal(value); expect(setEventCause).to.equal('explicit'); expect(setEventRemoved).to.equal(false); expect(removeEventCookie.name).to.equal(name); expect(removeEventCookie.value).to.equal(value); expect(removeEventCause).to.equal('explicit'); expect(removeEventRemoved).to.equal(true); }); describe('ses.cookies.flushStore()', async () => { it('flushes the cookies to disk', async () => { const name = 'foo'; const value = 'bar'; const { cookies } = session.defaultSession; await cookies.set({ url, name, value }); await cookies.flushStore(); }); }); it('should survive an app restart for persistent partition', async function () { this.timeout(60000); const appPath = path.join(fixtures, 'api', 'cookie-app'); const runAppWithPhase = (phase: string) => { return new Promise((resolve) => { let output = ''; const appProcess = ChildProcess.spawn( process.execPath, [appPath], { env: { PHASE: phase, ...process.env } } ); appProcess.stdout.on('data', data => { output += data; }); appProcess.on('exit', () => { resolve(output.replace(/(\r\n|\n|\r)/gm, '')); }); }); }; expect(await runAppWithPhase('one')).to.equal('011'); expect(await runAppWithPhase('two')).to.equal('110'); }); }); describe('ses.clearStorageData(options)', () => { afterEach(closeAllWindows); it('clears localstorage data', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadFile(path.join(fixtures, 'api', 'localstorage.html')); const options = { origin: 'file://', storages: ['localstorage'], quotas: ['persistent'] }; await w.webContents.session.clearStorageData(options); while (await w.webContents.executeJavaScript('localStorage.length') !== 0) { // The storage clear isn't instantly visible to the renderer, so keep // trying until it is. } }); }); describe('will-download event', () => { afterEach(closeAllWindows); it('can cancel default download behavior', async () => { const w = new BrowserWindow({ show: false }); const mockFile = Buffer.alloc(1024); const contentDisposition = 'inline; filename="mockFile.txt"'; const downloadServer = http.createServer((req, res) => { res.writeHead(200, { 'Content-Length': mockFile.length, 'Content-Type': 'application/plain', 'Content-Disposition': contentDisposition }); res.end(mockFile); downloadServer.close(); }); await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve)); const port = (downloadServer.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}/`; const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => { w.webContents.session.once('will-download', function (e, item) { e.preventDefault(); resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item }); }); }); w.loadURL(url); const { item, itemUrl, itemFilename } = await downloadPrevented; expect(itemUrl).to.equal(url); expect(itemFilename).to.equal('mockFile.txt'); // Delay till the next tick. await new Promise<void>(resolve => setImmediate(() => resolve())); expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed'); }); }); describe('ses.protocol', () => { const partitionName = 'temp'; const protocolName = 'sp'; let customSession: Session; const protocol = session.defaultSession.protocol; const handler = (ignoredError: any, callback: Function) => { callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' }); }; beforeEach(async () => { customSession = session.fromPartition(partitionName); await customSession.protocol.registerStringProtocol(protocolName, handler); }); afterEach(async () => { await customSession.protocol.unregisterProtocol(protocolName); customSession = null as any; }); afterEach(closeAllWindows); it('does not affect defaultSession', () => { const result1 = protocol.isProtocolRegistered(protocolName); expect(result1).to.equal(false); const result2 = customSession.protocol.isProtocolRegistered(protocolName); expect(result2).to.equal(true); }); it('handles requests from partition', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: partitionName, nodeIntegration: true, contextIsolation: false } }); customSession = session.fromPartition(partitionName); await customSession.protocol.registerStringProtocol(protocolName, handler); w.loadURL(`${protocolName}://fake-host`); await emittedOnce(ipcMain, 'hello'); }); }); describe('ses.setProxy(options)', () => { let server: http.Server; let customSession: Electron.Session; let created = false; beforeEach(async () => { customSession = session.fromPartition('proxyconfig'); if (!created) { // Work around for https://github.com/electron/electron/issues/26166 to // reduce flake await delay(100); created = true; } }); afterEach(() => { if (server) { server.close(); } customSession = null as any; }); it('allows configuring proxy settings', async () => { const config = { proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows removing the implicit bypass rules for localhost', async () => { const config = { proxyRules: 'http=myproxy:80', proxyBypassRules: '<-loopback>' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://localhost'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows configuring proxy settings with pacScript', async () => { server = http.createServer((req, res) => { const pac = ` function FindProxyForURL(url, host) { return "PROXY myproxy:8132"; } `; res.writeHead(200, { 'Content-Type': 'application/x-ns-proxy-autoconfig' }); res.end(pac); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); { const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal('PROXY myproxy:8132'); } { const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal('PROXY myproxy:8132'); } }); it('allows bypassing proxy settings', async () => { const config = { proxyRules: 'http=myproxy:80', proxyBypassRules: '<local>' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `direct`', async () => { const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `auto_detect`', async () => { const config = { mode: 'auto_detect' as any }; await customSession.setProxy(config); }); it('allows configuring proxy settings with mode `pac_script`', async () => { const config = { mode: 'pac_script' as any }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `fixed_servers`', async () => { const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows configuring proxy settings with mode `system`', async () => { const config = { mode: 'system' as any }; await customSession.setProxy(config); }); it('disallows configuring proxy settings with mode `invalid`', async () => { const config = { mode: 'invalid' as any }; await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/); }); it('reload proxy configuration', async () => { let proxyPort = 8132; server = http.createServer((req, res) => { const pac = ` function FindProxyForURL(url, host) { return "PROXY myproxy:${proxyPort}"; } `; res.writeHead(200, { 'Content-Type': 'application/x-ns-proxy-autoconfig' }); res.end(pac); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); { const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`); } { proxyPort = 8133; await customSession.forceReloadProxyConfig(); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`); } }); }); describe('ses.getBlobData()', () => { const scheme = 'cors-blob'; const protocol = session.defaultSession.protocol; const url = `${scheme}://host`; after(async () => { await protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); it('returns blob data for uuid', (done) => { const postData = JSON.stringify({ type: 'blob', value: 'hello' }); const content = `<html> <script> let fd = new FormData(); fd.append('file', new Blob(['${postData}'], {type:'application/json'})); fetch('${url}', {method:'POST', body: fd }); </script> </html>`; protocol.registerStringProtocol(scheme, (request, callback) => { try { if (request.method === 'GET') { callback({ data: content, mimeType: 'text/html' }); } else if (request.method === 'POST') { const uuid = request.uploadData![1].blobUUID; expect(uuid).to.be.a('string'); session.defaultSession.getBlobData(uuid!).then(result => { try { expect(result.toString()).to.equal(postData); done(); } catch (e) { done(e); } }); } } catch (e) { done(e); } }); const w = new BrowserWindow({ show: false }); w.loadURL(url); }); }); describe('ses.setCertificateVerifyProc(callback)', () => { let server: http.Server; beforeEach((done) => { const certPath = path.join(fixtures, 'certificates'); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], rejectUnauthorized: false }; server = https.createServer(options, (req, res) => { res.writeHead(200); res.end('<title>hello</title>'); }); server.listen(0, '127.0.0.1', done); }); afterEach((done) => { server.close(done); }); afterEach(closeAllWindows); it('accepts the request when the callback is called with 0', async () => { const ses = session.fromPartition(`${Math.random()}`); let validate: () => void; ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => { if (hostname !== '127.0.0.1') return callback(-3); validate = () => { expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']); expect(errorCode).to.be.oneOf([-202, -200]); }; callback(0); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`); expect(w.webContents.getTitle()).to.equal('hello'); expect(validate!).not.to.be.undefined(); validate!(); }); it('rejects the request when the callback is called with -2', async () => { const ses = session.fromPartition(`${Math.random()}`); let validate: () => void; ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => { if (hostname !== '127.0.0.1') return callback(-3); validate = () => { expect(certificate.issuerName).to.equal('Intermediate CA'); expect(certificate.subjectName).to.equal('localhost'); expect(certificate.issuer.commonName).to.equal('Intermediate CA'); expect(certificate.subject.commonName).to.equal('localhost'); expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA'); expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA'); expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA'); expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA'); expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined); expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']); expect(isIssuedByKnownRoot).to.be.false(); }; callback(-2); }); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(url); expect(validate!).not.to.be.undefined(); validate!(); }); it('saves cached results', async () => { const ses = session.fromPartition(`${Math.random()}`); let numVerificationRequests = 0; ses.setCertificateVerifyProc((e, callback) => { if (e.hostname !== '127.0.0.1') return callback(-3); numVerificationRequests++; callback(-2); }); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/); await emittedOnce(w.webContents, 'did-stop-loading'); await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(url + '/test'); expect(numVerificationRequests).to.equal(1); }); it('does not cancel requests in other sessions', async () => { const ses1 = session.fromPartition(`${Math.random()}`); ses1.setCertificateVerifyProc((opts, cb) => cb(0)); const ses2 = session.fromPartition(`${Math.random()}`); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const req = net.request({ url, session: ses1, credentials: 'include' }); req.end(); setTimeout(() => { ses2.setCertificateVerifyProc((opts, callback) => callback(0)); }); await expect(new Promise<void>((resolve, reject) => { req.on('error', (err) => { reject(err); }); req.on('response', () => { resolve(); }); })).to.eventually.be.fulfilled(); }); }); describe('ses.clearAuthCache()', () => { it('can clear http auth info from cache', async () => { const ses = session.fromPartition('auth-cache'); const server = http.createServer((req, res) => { const credentials = auth(req); if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.end('authenticated'); } }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const fetch = (url: string) => new Promise((resolve, reject) => { const request = net.request({ url, session: ses }); request.on('response', (response) => { let data: string | null = null; response.on('data', (chunk) => { if (!data) { data = ''; } data += chunk; }); response.on('end', () => { if (!data) { reject(new Error('Empty response')); } else { resolve(data); } }); response.on('error', (error: any) => { reject(new Error(error)); }); }); request.on('error', (error: any) => { reject(new Error(error)); }); request.end(); }); // the first time should throw due to unauthenticated await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected(); // passing the password should let us in expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated'); // subsequently, the credentials are cached expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated'); await ses.clearAuthCache(); // once the cache is cleared, we should get an error again await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected(); }); }); describe('DownloadItem', () => { const mockPDF = Buffer.alloc(1024 * 1024 * 5); const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); const protocolName = 'custom-dl'; const contentDisposition = 'inline; filename="mock.pdf"'; let address: AddressInfo; let downloadServer: http.Server; before(async () => { downloadServer = http.createServer((req, res) => { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); }); await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve)); address = downloadServer.address() as AddressInfo; }); after(async () => { await new Promise(resolve => downloadServer.close(resolve)); }); afterEach(closeAllWindows); const isPathEqual = (path1: string, path2: string) => { return path.relative(path1, path2) === ''; }; const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => { expect(state).to.equal('completed'); expect(item.getFilename()).to.equal('mock.pdf'); expect(path.isAbsolute(item.savePath)).to.equal(true); expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true); if (isCustom) { expect(item.getURL()).to.equal(`${protocolName}://item`); } else { expect(item.getURL()).to.be.equal(`${url}:${address.port}/`); } expect(item.getMimeType()).to.equal('application/pdf'); expect(item.getReceivedBytes()).to.equal(mockPDF.length); expect(item.getTotalBytes()).to.equal(mockPDF.length); expect(item.getContentDisposition()).to.equal(contentDisposition); expect(fs.existsSync(downloadFilePath)).to.equal(true); fs.unlinkSync(downloadFilePath); }; it('can download using session.downloadURL', (done) => { const port = address.port; session.defaultSession.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item); done(); } catch (e) { done(e); } }); }); session.defaultSession.downloadURL(`${url}:${port}`); }); it('can download using WebContents.downloadURL', (done) => { const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`${url}:${port}`); }); it('can download from custom protocols using WebContents.downloadURL', (done) => { const protocol = session.defaultSession.protocol; const port = address.port; const handler = (ignoredError: any, callback: Function) => { callback({ url: `${url}:${port}` }); }; protocol.registerHttpProtocol(protocolName, handler); const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item, true); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`${protocolName}://item`); }); it('can download using WebView.downloadURL', async () => { const port = address.port; const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) { const webview = new (window as any).WebView(); webview.addEventListener('did-finish-load', () => { webview.downloadURL(`${url}:${port}/`); }); webview.src = `file://${fixtures}/api/blank.html`; document.body.appendChild(webview); } const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => { w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { resolve([state, item]); }); }); }); await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`); const [state, item] = await done; assertDownload(state, item); }); it('can cancel download', (done) => { const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { expect(state).to.equal('cancelled'); expect(item.getFilename()).to.equal('mock.pdf'); expect(item.getMimeType()).to.equal('application/pdf'); expect(item.getReceivedBytes()).to.equal(0); expect(item.getTotalBytes()).to.equal(mockPDF.length); expect(item.getContentDisposition()).to.equal(contentDisposition); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}/`); }); it('can generate a default filename', function (done) { if (process.env.APPVEYOR === 'True') { // FIXME(alexeykuzmin): Skip the test. // this.skip() return done(); } const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function () { try { expect(item.getFilename()).to.equal('download.pdf'); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}/?testFilename`); }); it('can set options for the save dialog', (done) => { const filePath = path.join(__dirname, 'fixtures', 'mock.pdf'); const port = address.port; const options = { window: null, title: 'title', message: 'message', buttonLabel: 'buttonLabel', nameFieldLabel: 'nameFieldLabel', defaultPath: '/', filters: [{ name: '1', extensions: ['.1', '.2'] }, { name: '2', extensions: ['.3', '.4', '.5'] }], showsTagField: true, securityScopedBookmarks: true }; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.setSavePath(filePath); item.setSaveDialogOptions(options); item.on('done', function () { try { expect(item.getSaveDialogOptions()).to.deep.equal(options); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}`); }); describe('when a save path is specified and the URL is unavailable', () => { it('does not display a save dialog and reports the done state as interrupted', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; if (item.getState() === 'interrupted') { item.resume(); } item.on('done', function (e, state) { try { expect(state).to.equal('interrupted'); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`); }); }); }); describe('ses.createInterruptedDownload(options)', () => { afterEach(closeAllWindows); it('can create an interrupted download item', async () => { const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); const options = { path: downloadFilePath, urlChain: ['http://127.0.0.1/'], mimeType: 'application/pdf', offset: 0, length: 5242880 }; const w = new BrowserWindow({ show: false }); const p = emittedOnce(w.webContents.session, 'will-download'); w.webContents.session.createInterruptedDownload(options); const [, item] = await p; expect(item.getState()).to.equal('interrupted'); item.cancel(); expect(item.getURLChain()).to.deep.equal(options.urlChain); expect(item.getMimeType()).to.equal(options.mimeType); expect(item.getReceivedBytes()).to.equal(options.offset); expect(item.getTotalBytes()).to.equal(options.length); expect(item.savePath).to.equal(downloadFilePath); }); it('can be resumed', async () => { const downloadFilePath = path.join(fixtures, 'logo.png'); const rangeServer = http.createServer((req, res) => { const options = { root: fixtures }; send(req, req.url!, options) .on('error', (error: any) => { throw error; }).pipe(res); }); try { await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve)); const port = (rangeServer.address() as AddressInfo).port; const w = new BrowserWindow({ show: false }); const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => { w.webContents.session.once('will-download', function (e, item) { item.setSavePath(downloadFilePath); item.on('done', function () { resolve(item); }); item.cancel(); }); }); const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`; w.webContents.downloadURL(downloadUrl); const item = await downloadCancelled; expect(item.getState()).to.equal('cancelled'); const options = { path: item.savePath, urlChain: item.getURLChain(), mimeType: item.getMimeType(), offset: item.getReceivedBytes(), length: item.getTotalBytes(), lastModified: item.getLastModifiedTime(), eTag: item.getETag() }; const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => { w.webContents.session.once('will-download', function (e, item) { expect(item.getState()).to.equal('interrupted'); item.setSavePath(downloadFilePath); item.resume(); item.on('done', function () { resolve(item); }); }); }); w.webContents.session.createInterruptedDownload(options); const completedItem = await downloadResumed; expect(completedItem.getState()).to.equal('completed'); expect(completedItem.getFilename()).to.equal('logo.png'); expect(completedItem.savePath).to.equal(downloadFilePath); expect(completedItem.getURL()).to.equal(downloadUrl); expect(completedItem.getMimeType()).to.equal('image/png'); expect(completedItem.getReceivedBytes()).to.equal(14022); expect(completedItem.getTotalBytes()).to.equal(14022); expect(fs.existsSync(downloadFilePath)).to.equal(true); } finally { rangeServer.close(); } }); }); describe('ses.setPermissionRequestHandler(handler)', () => { afterEach(closeAllWindows); it('cancels any pending requests when cleared', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler', nodeIntegration: true, contextIsolation: false } }); const ses = w.webContents.session; ses.setPermissionRequestHandler(() => { ses.setPermissionRequestHandler(null); }); ses.protocol.interceptStringProtocol('https', (req, cb) => { cb(`<html><script>(${remote})()</script></html>`); }); const result = emittedOnce(require('electron').ipcMain, 'message'); function remote () { (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => { require('electron').ipcRenderer.send('message', err.name); }); } await w.loadURL('https://myfakesite'); const [, name] = await result; expect(name).to.deep.equal('SecurityError'); }); }); describe('ses.setPermissionCheckHandler(handler)', () => { afterEach(closeAllWindows); it('details provides requestingURL for mainFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler' } }); const ses = w.webContents.session; const loadUrl = 'https://myfakesite/'; let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails; ses.protocol.interceptStringProtocol('https', (req, cb) => { cb('<html><script>console.log(\'test\');</script></html>'); }); ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => { if (permission === 'clipboard-read') { handlerDetails = details; return true; } return false; }); const readClipboardPermission: any = () => { return w.webContents.executeJavaScript(` navigator.permissions.query({name: 'clipboard-read'}) .then(permission => permission.state).catch(err => err.message); `, true); }; await w.loadURL(loadUrl); const state = await readClipboardPermission(); expect(state).to.equal('granted'); expect(handlerDetails!.requestingUrl).to.equal(loadUrl); }); it('details provides requestingURL for cross origin subFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler' } }); const ses = w.webContents.session; const loadUrl = 'https://myfakesite/'; let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails; ses.protocol.interceptStringProtocol('https', (req, cb) => { cb('<html><script>console.log(\'test\');</script></html>'); }); ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => { if (permission === 'clipboard-read') { handlerDetails = details; return true; } return false; }); const readClipboardPermission: any = (frame: WebFrameMain) => { return frame.executeJavaScript(` navigator.permissions.query({name: 'clipboard-read'}) .then(permission => permission.state).catch(err => err.message); `, true); }; await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe'); iframe.src = '${loadUrl}'; document.body.appendChild(iframe); null; `); const [,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-finish-load'); const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId)); expect(state).to.equal('granted'); expect(handlerDetails!.requestingUrl).to.equal(loadUrl); expect(handlerDetails!.isMainFrame).to.be.false(); expect(handlerDetails!.embeddingOrigin).to.equal('file:///'); }); }); describe('ses.isPersistent()', () => { afterEach(closeAllWindows); it('returns default session as persistent', () => { const w = new BrowserWindow({ show: false }); const ses = w.webContents.session; expect(ses.isPersistent()).to.be.true(); }); it('returns persist: session as persistent', () => { const ses = session.fromPartition(`persist:${Math.random()}`); expect(ses.isPersistent()).to.be.true(); }); it('returns temporary session as not persistent', () => { const ses = session.fromPartition(`${Math.random()}`); expect(ses.isPersistent()).to.be.false(); }); }); describe('ses.setUserAgent()', () => { afterEach(closeAllWindows); it('can be retrieved with getUserAgent()', () => { const userAgent = 'test-agent'; const ses = session.fromPartition('' + Math.random()); ses.setUserAgent(userAgent); expect(ses.getUserAgent()).to.equal(userAgent); }); it('sets the User-Agent header for web requests made from renderers', async () => { const userAgent = 'test-agent'; const ses = session.fromPartition('' + Math.random()); ses.setUserAgent(userAgent, 'en-US,fr,de'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); let headers: http.IncomingHttpHeaders | null = null; const server = http.createServer((req, res) => { headers = req.headers; res.end(); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); expect(headers!['user-agent']).to.equal(userAgent); expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8'); }); }); describe('session-created event', () => { it('is emitted when a session is created', async () => { const sessionCreated = emittedOnce(app, 'session-created'); const session1 = session.fromPartition('' + Math.random()); const [session2] = await sessionCreated; expect(session1).to.equal(session2); }); }); describe('session.storagePage', () => { it('returns a string', () => { expect(session.defaultSession.storagePath).to.be.a('string'); }); it('returns null for in memory sessions', () => { expect(session.fromPartition('in-memory').storagePath).to.equal(null); }); it('returns different paths for partitions and the default session', () => { expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath); }); it('returns different paths for different partitions', () => { expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath); }); }); describe('session.setCodeCachePath()', () => { it('throws when relative or empty path is provided', () => { expect(() => { session.defaultSession.setCodeCachePath('../fixtures'); }).to.throw('Absolute path must be provided to store code cache.'); expect(() => { session.defaultSession.setCodeCachePath(''); }).to.throw('Absolute path must be provided to store code cache.'); expect(() => { session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache')); }).to.not.throw(); }); }); describe('ses.setSSLConfig()', () => { it('can disable cipher suites', async () => { const ses = session.fromPartition('' + Math.random()); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); const server = https.createServer({ key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], minVersion: 'TLSv1.2', maxVersion: 'TLSv1.2', ciphers: 'AES128-GCM-SHA256' }, (req, res) => { res.end('hi'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); defer(() => server.close()); const { port } = server.address() as AddressInfo; function request () { return new Promise((resolve, reject) => { const r = net.request({ url: `https://127.0.0.1:${port}`, session: ses }); r.on('response', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk.toString('utf8'); }); res.on('end', () => { resolve(data); }); }); r.on('error', (err) => { reject(err); }); r.end(); }); } await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/); ses.setSSLConfig({ disabledCipherSuites: [0x009C] }); await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,398
[Bug]: session.getBlobData never resolves with blob sizes > 65536
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 (21E258) ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When running `session.getBlobData` on a blob UUID from an `onBeforeRequest` handler, I expect the resulting promise to resolve successfully to a buffer when the blob size is <<< RAM size. According to https://source.chromium.org/chromium/chromium/src/+/main:storage/browser/blob/blob_memory_controller.cc?q=CalculateBlobStorageLimitsImpl&ss=chromium, a blob of size 65537 should be handled correctly. ### Actual Behavior When calling `session.getBlobData` on a blob with size > 65536, the resulting promise never resolves. ### Testcase Gist URL https://gist.github.com/b3b9955084b145c77987e4dbc6c81078 ### Additional Information This issue appears to be a possible duplicate of https://github.com/electron/electron/issues/33081, though the other issue includes very little additional information, so I have filed a separate issue to be safe. I did a bit of digging through the Electron glue source, and I found the following: https://github.com/electron/electron/blob/61374019c03ab1af8584550277318ba7c2adb0ca/shell/browser/api/electron_api_session.cc#L725-L735 https://github.com/electron/electron/blob/c4ea33d1bf6faf8ca685e67e63b197d89efa9870/shell/browser/api/electron_api_data_pipe_holder.h#L33-L35 I suspect that this is related.
https://github.com/electron/electron/issues/34398
https://github.com/electron/electron/pull/35277
3a6d6ff0083408588af10a8931f881d7ee134622
e3efa16415ac090b38bd87d6b509ccecc90cefa0
2022-06-01T00:55:38Z
c++
2022-09-07T21:47:06Z
shell/browser/api/electron_api_data_pipe_holder.cc
// Copyright (c) 2019 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_data_pipe_holder.h" #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/base/net_errors.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/key_weak_map.h" #include "shell/common/node_includes.h" namespace electron::api { namespace { // Incremental ID. int g_next_id = 0; // Map that manages all the DataPipeHolder objects. KeyWeakMap<std::string>& AllDataPipeHolders() { static base::NoDestructor<KeyWeakMap<std::string>> weak_map; return *weak_map.get(); } // Utility class to read from data pipe. class DataPipeReader { public: DataPipeReader(gin_helper::Promise<v8::Local<v8::Value>> promise, mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter) : promise_(std::move(promise)), data_pipe_getter_(std::move(data_pipe_getter)), handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()) { // Get a new data pipe and start. mojo::ScopedDataPipeProducerHandle producer_handle; CHECK_EQ(mojo::CreateDataPipe(nullptr, producer_handle, data_pipe_), MOJO_RESULT_OK); data_pipe_getter_->Read(std::move(producer_handle), base::BindOnce(&DataPipeReader::ReadCallback, weak_factory_.GetWeakPtr())); handle_watcher_.Watch(data_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, base::BindRepeating(&DataPipeReader::OnHandleReadable, weak_factory_.GetWeakPtr())); } ~DataPipeReader() = default; // disable copy DataPipeReader(const DataPipeReader&) = delete; DataPipeReader& operator=(const DataPipeReader&) = delete; private: // Callback invoked by DataPipeGetter::Read. void ReadCallback(int32_t status, uint64_t size) { if (status != net::OK) { OnFailure(); return; } buffer_.resize(size); head_ = &buffer_.front(); remaining_size_ = size; handle_watcher_.ArmOrNotify(); } // Called by |handle_watcher_| when data is available or the pipe was closed, // and there's a pending Read() call. void OnHandleReadable(MojoResult result) { if (result != MOJO_RESULT_OK) { OnFailure(); return; } // Read. uint32_t length = remaining_size_; result = data_pipe_->ReadData(head_, &length, MOJO_READ_DATA_FLAG_NONE); if (result == MOJO_RESULT_OK) { // success remaining_size_ -= length; head_ += length; if (remaining_size_ == 0) OnSuccess(); } else if (result == MOJO_RESULT_SHOULD_WAIT) { // IO pending handle_watcher_.ArmOrNotify(); } else { // error OnFailure(); } } void OnFailure() { promise_.RejectWithErrorMessage("Could not get blob data"); delete this; } void OnSuccess() { // Copy the buffer to JS. // TODO(nornagon): make this zero-copy by allocating the array buffer // inside the sandbox v8::HandleScope handle_scope(promise_.isolate()); v8::Local<v8::Value> buffer = node::Buffer::Copy(promise_.isolate(), &buffer_.front(), buffer_.size()) .ToLocalChecked(); promise_.Resolve(buffer); // Destroy data pipe. handle_watcher_.Cancel(); delete this; } gin_helper::Promise<v8::Local<v8::Value>> promise_; mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter_; mojo::ScopedDataPipeConsumerHandle data_pipe_; mojo::SimpleWatcher handle_watcher_; // Stores read data. std::vector<char> buffer_; // The head of buffer. char* head_ = nullptr; // Remaining data to read. uint64_t remaining_size_ = 0; base::WeakPtrFactory<DataPipeReader> weak_factory_{this}; }; } // namespace gin::WrapperInfo DataPipeHolder::kWrapperInfo = {gin::kEmbedderNativeGin}; DataPipeHolder::DataPipeHolder(const network::DataElement& element) : id_(base::NumberToString(++g_next_id)) { data_pipe_.Bind( element.As<network::DataElementDataPipe>().CloneDataPipeGetter()); } DataPipeHolder::~DataPipeHolder() = default; v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) { gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!data_pipe_) { promise.RejectWithErrorMessage("Could not get blob data"); return handle; } new DataPipeReader(std::move(promise), std::move(data_pipe_)); return handle; } // static gin::Handle<DataPipeHolder> DataPipeHolder::Create( v8::Isolate* isolate, const network::DataElement& element) { auto handle = gin::CreateHandle(isolate, new DataPipeHolder(element)); AllDataPipeHolders().Set(isolate, handle->id(), handle->GetWrapper(isolate).ToLocalChecked()); return handle; } // static gin::Handle<DataPipeHolder> DataPipeHolder::From(v8::Isolate* isolate, const std::string& id) { v8::MaybeLocal<v8::Object> object = AllDataPipeHolders().Get(isolate, id); if (!object.IsEmpty()) { gin::Handle<DataPipeHolder> handle; if (gin::ConvertFromV8(isolate, object.ToLocalChecked(), &handle)) return handle; } return gin::Handle<DataPipeHolder>(); } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
34,398
[Bug]: session.getBlobData never resolves with blob sizes > 65536
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 (21E258) ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When running `session.getBlobData` on a blob UUID from an `onBeforeRequest` handler, I expect the resulting promise to resolve successfully to a buffer when the blob size is <<< RAM size. According to https://source.chromium.org/chromium/chromium/src/+/main:storage/browser/blob/blob_memory_controller.cc?q=CalculateBlobStorageLimitsImpl&ss=chromium, a blob of size 65537 should be handled correctly. ### Actual Behavior When calling `session.getBlobData` on a blob with size > 65536, the resulting promise never resolves. ### Testcase Gist URL https://gist.github.com/b3b9955084b145c77987e4dbc6c81078 ### Additional Information This issue appears to be a possible duplicate of https://github.com/electron/electron/issues/33081, though the other issue includes very little additional information, so I have filed a separate issue to be safe. I did a bit of digging through the Electron glue source, and I found the following: https://github.com/electron/electron/blob/61374019c03ab1af8584550277318ba7c2adb0ca/shell/browser/api/electron_api_session.cc#L725-L735 https://github.com/electron/electron/blob/c4ea33d1bf6faf8ca685e67e63b197d89efa9870/shell/browser/api/electron_api_data_pipe_holder.h#L33-L35 I suspect that this is related.
https://github.com/electron/electron/issues/34398
https://github.com/electron/electron/pull/35277
3a6d6ff0083408588af10a8931f881d7ee134622
e3efa16415ac090b38bd87d6b509ccecc90cefa0
2022-06-01T00:55:38Z
c++
2022-09-07T21:47:06Z
spec/api-session-spec.ts
import { expect } from 'chai'; import * as http from 'http'; import * as https from 'https'; import * as path from 'path'; import * as fs from 'fs'; import * as ChildProcess from 'child_process'; import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main'; import * as send from 'send'; import * as auth from 'basic-auth'; import { closeAllWindows } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { defer, delay } from './spec-helpers'; import { AddressInfo } from 'net'; /* The whole session API doesn't use standard callbacks */ /* eslint-disable standard/no-callback-literal */ describe('session module', () => { const fixtures = path.resolve(__dirname, 'fixtures'); const url = 'http://127.0.0.1'; describe('session.defaultSession', () => { it('returns the default session', () => { expect(session.defaultSession).to.equal(session.fromPartition('')); }); }); describe('session.fromPartition(partition, options)', () => { it('returns existing session with same partition', () => { expect(session.fromPartition('test')).to.equal(session.fromPartition('test')); }); }); describe('ses.cookies', () => { const name = '0'; const value = '0'; afterEach(closeAllWindows); // Clear cookie of defaultSession after each test. afterEach(async () => { const { cookies } = session.defaultSession; const cs = await cookies.get({ url }); for (const c of cs) { await cookies.remove(url, c.name); } }); it('should get cookies', async () => { const server = http.createServer((req, res) => { res.setHeader('Set-Cookie', [`${name}=${value}`]); res.end('finished'); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const { port } = server.address() as AddressInfo; const w = new BrowserWindow({ show: false }); await w.loadURL(`${url}:${port}`); const list = await w.webContents.session.cookies.get({ url }); const cookie = list.find(cookie => cookie.name === name); expect(cookie).to.exist.and.to.have.property('value', value); }); it('sets cookies', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.equal(name); expect(c.value).to.equal(value); expect(c.session).to.equal(false); }); it('sets session cookies', async () => { const { cookies } = session.defaultSession; const name = '2'; const value = '1'; await cookies.set({ url, name, value }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.equal(name); expect(c.value).to.equal(value); expect(c.session).to.equal(true); }); it('sets cookies without name', async () => { const { cookies } = session.defaultSession; const value = '3'; await cookies.set({ url, value }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.be.empty(); expect(c.value).to.equal(value); }); for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) { it(`sets cookies with samesite=${sameSite}`, async () => { const { cookies } = session.defaultSession; const value = 'hithere'; await cookies.set({ url, value, sameSite }); const c = (await cookies.get({ url }))[0]; expect(c.name).to.be.empty(); expect(c.value).to.equal(value); expect(c.sameSite).to.equal(sameSite); }); } it('fails to set cookies with samesite=garbage', async () => { const { cookies } = session.defaultSession; const value = 'hithere'; await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value'); }); it('gets cookies without url', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const cs = await cookies.get({ domain: '127.0.0.1' }); expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); }); it('yields an error when setting a cookie with missing required fields', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: '', name, value }) ).to.eventually.be.rejectedWith('Failed to get cookie domain'); }); it('yields an error when setting a cookie with an invalid URL', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: 'asdf', name, value }) ).to.eventually.be.rejectedWith('Failed to get cookie domain'); }); it('should overwrite previous cookies', async () => { const { cookies } = session.defaultSession; const name = 'DidOverwrite'; for (const value of ['No', 'Yes']) { await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const list = await cookies.get({ url }); expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true); } }); it('should remove cookies', async () => { const { cookies } = session.defaultSession; const name = '2'; const value = '2'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); await cookies.remove(url, name); const list = await cookies.get({ url }); expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false); }); it.skip('should set cookie for standard scheme', async () => { const { cookies } = session.defaultSession; const domain = 'fake-host'; const url = `${standardScheme}://${domain}`; const name = 'custom'; const value = '1'; await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const list = await cookies.get({ url }); expect(list).to.have.lengthOf(1); expect(list[0]).to.have.property('name', name); expect(list[0]).to.have.property('value', value); expect(list[0]).to.have.property('domain', domain); }); it('emits a changed event when a cookie is added or removed', async () => { const { cookies } = session.fromPartition('cookies-changed'); const name = 'foo'; const value = 'bar'; const a = emittedOnce(cookies, 'changed'); await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const [, setEventCookie, setEventCause, setEventRemoved] = await a; const b = emittedOnce(cookies, 'changed'); await cookies.remove(url, name); const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b; expect(setEventCookie.name).to.equal(name); expect(setEventCookie.value).to.equal(value); expect(setEventCause).to.equal('explicit'); expect(setEventRemoved).to.equal(false); expect(removeEventCookie.name).to.equal(name); expect(removeEventCookie.value).to.equal(value); expect(removeEventCause).to.equal('explicit'); expect(removeEventRemoved).to.equal(true); }); describe('ses.cookies.flushStore()', async () => { it('flushes the cookies to disk', async () => { const name = 'foo'; const value = 'bar'; const { cookies } = session.defaultSession; await cookies.set({ url, name, value }); await cookies.flushStore(); }); }); it('should survive an app restart for persistent partition', async function () { this.timeout(60000); const appPath = path.join(fixtures, 'api', 'cookie-app'); const runAppWithPhase = (phase: string) => { return new Promise((resolve) => { let output = ''; const appProcess = ChildProcess.spawn( process.execPath, [appPath], { env: { PHASE: phase, ...process.env } } ); appProcess.stdout.on('data', data => { output += data; }); appProcess.on('exit', () => { resolve(output.replace(/(\r\n|\n|\r)/gm, '')); }); }); }; expect(await runAppWithPhase('one')).to.equal('011'); expect(await runAppWithPhase('two')).to.equal('110'); }); }); describe('ses.clearStorageData(options)', () => { afterEach(closeAllWindows); it('clears localstorage data', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadFile(path.join(fixtures, 'api', 'localstorage.html')); const options = { origin: 'file://', storages: ['localstorage'], quotas: ['persistent'] }; await w.webContents.session.clearStorageData(options); while (await w.webContents.executeJavaScript('localStorage.length') !== 0) { // The storage clear isn't instantly visible to the renderer, so keep // trying until it is. } }); }); describe('will-download event', () => { afterEach(closeAllWindows); it('can cancel default download behavior', async () => { const w = new BrowserWindow({ show: false }); const mockFile = Buffer.alloc(1024); const contentDisposition = 'inline; filename="mockFile.txt"'; const downloadServer = http.createServer((req, res) => { res.writeHead(200, { 'Content-Length': mockFile.length, 'Content-Type': 'application/plain', 'Content-Disposition': contentDisposition }); res.end(mockFile); downloadServer.close(); }); await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve)); const port = (downloadServer.address() as AddressInfo).port; const url = `http://127.0.0.1:${port}/`; const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => { w.webContents.session.once('will-download', function (e, item) { e.preventDefault(); resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item }); }); }); w.loadURL(url); const { item, itemUrl, itemFilename } = await downloadPrevented; expect(itemUrl).to.equal(url); expect(itemFilename).to.equal('mockFile.txt'); // Delay till the next tick. await new Promise<void>(resolve => setImmediate(() => resolve())); expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed'); }); }); describe('ses.protocol', () => { const partitionName = 'temp'; const protocolName = 'sp'; let customSession: Session; const protocol = session.defaultSession.protocol; const handler = (ignoredError: any, callback: Function) => { callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' }); }; beforeEach(async () => { customSession = session.fromPartition(partitionName); await customSession.protocol.registerStringProtocol(protocolName, handler); }); afterEach(async () => { await customSession.protocol.unregisterProtocol(protocolName); customSession = null as any; }); afterEach(closeAllWindows); it('does not affect defaultSession', () => { const result1 = protocol.isProtocolRegistered(protocolName); expect(result1).to.equal(false); const result2 = customSession.protocol.isProtocolRegistered(protocolName); expect(result2).to.equal(true); }); it('handles requests from partition', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: partitionName, nodeIntegration: true, contextIsolation: false } }); customSession = session.fromPartition(partitionName); await customSession.protocol.registerStringProtocol(protocolName, handler); w.loadURL(`${protocolName}://fake-host`); await emittedOnce(ipcMain, 'hello'); }); }); describe('ses.setProxy(options)', () => { let server: http.Server; let customSession: Electron.Session; let created = false; beforeEach(async () => { customSession = session.fromPartition('proxyconfig'); if (!created) { // Work around for https://github.com/electron/electron/issues/26166 to // reduce flake await delay(100); created = true; } }); afterEach(() => { if (server) { server.close(); } customSession = null as any; }); it('allows configuring proxy settings', async () => { const config = { proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows removing the implicit bypass rules for localhost', async () => { const config = { proxyRules: 'http=myproxy:80', proxyBypassRules: '<-loopback>' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://localhost'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows configuring proxy settings with pacScript', async () => { server = http.createServer((req, res) => { const pac = ` function FindProxyForURL(url, host) { return "PROXY myproxy:8132"; } `; res.writeHead(200, { 'Content-Type': 'application/x-ns-proxy-autoconfig' }); res.end(pac); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); { const config = { pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal('PROXY myproxy:8132'); } { const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal('PROXY myproxy:8132'); } }); it('allows bypassing proxy settings', async () => { const config = { proxyRules: 'http=myproxy:80', proxyBypassRules: '<local>' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `direct`', async () => { const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `auto_detect`', async () => { const config = { mode: 'auto_detect' as any }; await customSession.setProxy(config); }); it('allows configuring proxy settings with mode `pac_script`', async () => { const config = { mode: 'pac_script' as any }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('DIRECT'); }); it('allows configuring proxy settings with mode `fixed_servers`', async () => { const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' }; await customSession.setProxy(config); const proxy = await customSession.resolveProxy('http://example.com/'); expect(proxy).to.equal('PROXY myproxy:80'); }); it('allows configuring proxy settings with mode `system`', async () => { const config = { mode: 'system' as any }; await customSession.setProxy(config); }); it('disallows configuring proxy settings with mode `invalid`', async () => { const config = { mode: 'invalid' as any }; await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/); }); it('reload proxy configuration', async () => { let proxyPort = 8132; server = http.createServer((req, res) => { const pac = ` function FindProxyForURL(url, host) { return "PROXY myproxy:${proxyPort}"; } `; res.writeHead(200, { 'Content-Type': 'application/x-ns-proxy-autoconfig' }); res.end(pac); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const config = { mode: 'pac_script' as any, pacScript: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }; await customSession.setProxy(config); { const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`); } { proxyPort = 8133; await customSession.forceReloadProxyConfig(); const proxy = await customSession.resolveProxy('https://google.com'); expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`); } }); }); describe('ses.getBlobData()', () => { const scheme = 'cors-blob'; const protocol = session.defaultSession.protocol; const url = `${scheme}://host`; after(async () => { await protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); it('returns blob data for uuid', (done) => { const postData = JSON.stringify({ type: 'blob', value: 'hello' }); const content = `<html> <script> let fd = new FormData(); fd.append('file', new Blob(['${postData}'], {type:'application/json'})); fetch('${url}', {method:'POST', body: fd }); </script> </html>`; protocol.registerStringProtocol(scheme, (request, callback) => { try { if (request.method === 'GET') { callback({ data: content, mimeType: 'text/html' }); } else if (request.method === 'POST') { const uuid = request.uploadData![1].blobUUID; expect(uuid).to.be.a('string'); session.defaultSession.getBlobData(uuid!).then(result => { try { expect(result.toString()).to.equal(postData); done(); } catch (e) { done(e); } }); } } catch (e) { done(e); } }); const w = new BrowserWindow({ show: false }); w.loadURL(url); }); }); describe('ses.setCertificateVerifyProc(callback)', () => { let server: http.Server; beforeEach((done) => { const certPath = path.join(fixtures, 'certificates'); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], rejectUnauthorized: false }; server = https.createServer(options, (req, res) => { res.writeHead(200); res.end('<title>hello</title>'); }); server.listen(0, '127.0.0.1', done); }); afterEach((done) => { server.close(done); }); afterEach(closeAllWindows); it('accepts the request when the callback is called with 0', async () => { const ses = session.fromPartition(`${Math.random()}`); let validate: () => void; ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => { if (hostname !== '127.0.0.1') return callback(-3); validate = () => { expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']); expect(errorCode).to.be.oneOf([-202, -200]); }; callback(0); }); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(`https://127.0.0.1:${(server.address() as AddressInfo).port}`); expect(w.webContents.getTitle()).to.equal('hello'); expect(validate!).not.to.be.undefined(); validate!(); }); it('rejects the request when the callback is called with -2', async () => { const ses = session.fromPartition(`${Math.random()}`); let validate: () => void; ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => { if (hostname !== '127.0.0.1') return callback(-3); validate = () => { expect(certificate.issuerName).to.equal('Intermediate CA'); expect(certificate.subjectName).to.equal('localhost'); expect(certificate.issuer.commonName).to.equal('Intermediate CA'); expect(certificate.subject.commonName).to.equal('localhost'); expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA'); expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA'); expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA'); expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA'); expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined); expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']); expect(isIssuedByKnownRoot).to.be.false(); }; callback(-2); }); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(url)).to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(url); expect(validate!).not.to.be.undefined(); validate!(); }); it('saves cached results', async () => { const ses = session.fromPartition(`${Math.random()}`); let numVerificationRequests = 0; ses.setCertificateVerifyProc((e, callback) => { if (e.hostname !== '127.0.0.1') return callback(-3); numVerificationRequests++; callback(-2); }); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(url), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/); await emittedOnce(w.webContents, 'did-stop-loading'); await expect(w.loadURL(url + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(url + '/test'); expect(numVerificationRequests).to.equal(1); }); it('does not cancel requests in other sessions', async () => { const ses1 = session.fromPartition(`${Math.random()}`); ses1.setCertificateVerifyProc((opts, cb) => cb(0)); const ses2 = session.fromPartition(`${Math.random()}`); const url = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; const req = net.request({ url, session: ses1, credentials: 'include' }); req.end(); setTimeout(() => { ses2.setCertificateVerifyProc((opts, callback) => callback(0)); }); await expect(new Promise<void>((resolve, reject) => { req.on('error', (err) => { reject(err); }); req.on('response', () => { resolve(); }); })).to.eventually.be.fulfilled(); }); }); describe('ses.clearAuthCache()', () => { it('can clear http auth info from cache', async () => { const ses = session.fromPartition('auth-cache'); const server = http.createServer((req, res) => { const credentials = auth(req); if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.end('authenticated'); } }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const fetch = (url: string) => new Promise((resolve, reject) => { const request = net.request({ url, session: ses }); request.on('response', (response) => { let data: string | null = null; response.on('data', (chunk) => { if (!data) { data = ''; } data += chunk; }); response.on('end', () => { if (!data) { reject(new Error('Empty response')); } else { resolve(data); } }); response.on('error', (error: any) => { reject(new Error(error)); }); }); request.on('error', (error: any) => { reject(new Error(error)); }); request.end(); }); // the first time should throw due to unauthenticated await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected(); // passing the password should let us in expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated'); // subsequently, the credentials are cached expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated'); await ses.clearAuthCache(); // once the cache is cleared, we should get an error again await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected(); }); }); describe('DownloadItem', () => { const mockPDF = Buffer.alloc(1024 * 1024 * 5); const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); const protocolName = 'custom-dl'; const contentDisposition = 'inline; filename="mock.pdf"'; let address: AddressInfo; let downloadServer: http.Server; before(async () => { downloadServer = http.createServer((req, res) => { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); }); await new Promise<void>(resolve => downloadServer.listen(0, '127.0.0.1', resolve)); address = downloadServer.address() as AddressInfo; }); after(async () => { await new Promise(resolve => downloadServer.close(resolve)); }); afterEach(closeAllWindows); const isPathEqual = (path1: string, path2: string) => { return path.relative(path1, path2) === ''; }; const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => { expect(state).to.equal('completed'); expect(item.getFilename()).to.equal('mock.pdf'); expect(path.isAbsolute(item.savePath)).to.equal(true); expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true); if (isCustom) { expect(item.getURL()).to.equal(`${protocolName}://item`); } else { expect(item.getURL()).to.be.equal(`${url}:${address.port}/`); } expect(item.getMimeType()).to.equal('application/pdf'); expect(item.getReceivedBytes()).to.equal(mockPDF.length); expect(item.getTotalBytes()).to.equal(mockPDF.length); expect(item.getContentDisposition()).to.equal(contentDisposition); expect(fs.existsSync(downloadFilePath)).to.equal(true); fs.unlinkSync(downloadFilePath); }; it('can download using session.downloadURL', (done) => { const port = address.port; session.defaultSession.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item); done(); } catch (e) { done(e); } }); }); session.defaultSession.downloadURL(`${url}:${port}`); }); it('can download using WebContents.downloadURL', (done) => { const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`${url}:${port}`); }); it('can download from custom protocols using WebContents.downloadURL', (done) => { const protocol = session.defaultSession.protocol; const port = address.port; const handler = (ignoredError: any, callback: Function) => { callback({ url: `${url}:${port}` }); }; protocol.registerHttpProtocol(protocolName, handler); const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { assertDownload(state, item, true); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`${protocolName}://item`); }); it('can download using WebView.downloadURL', async () => { const port = address.port; const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); await w.loadURL('about:blank'); function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) { const webview = new (window as any).WebView(); webview.addEventListener('did-finish-load', () => { webview.downloadURL(`${url}:${port}/`); }); webview.src = `file://${fixtures}/api/blank.html`; document.body.appendChild(webview); } const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => { w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { resolve([state, item]); }); }); }); await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`); const [state, item] = await done; assertDownload(state, item); }); it('can cancel download', (done) => { const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function (e, state) { try { expect(state).to.equal('cancelled'); expect(item.getFilename()).to.equal('mock.pdf'); expect(item.getMimeType()).to.equal('application/pdf'); expect(item.getReceivedBytes()).to.equal(0); expect(item.getTotalBytes()).to.equal(mockPDF.length); expect(item.getContentDisposition()).to.equal(contentDisposition); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}/`); }); it('can generate a default filename', function (done) { if (process.env.APPVEYOR === 'True') { // FIXME(alexeykuzmin): Skip the test. // this.skip() return done(); } const port = address.port; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; item.on('done', function () { try { expect(item.getFilename()).to.equal('download.pdf'); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}/?testFilename`); }); it('can set options for the save dialog', (done) => { const filePath = path.join(__dirname, 'fixtures', 'mock.pdf'); const port = address.port; const options = { window: null, title: 'title', message: 'message', buttonLabel: 'buttonLabel', nameFieldLabel: 'nameFieldLabel', defaultPath: '/', filters: [{ name: '1', extensions: ['.1', '.2'] }, { name: '2', extensions: ['.3', '.4', '.5'] }], showsTagField: true, securityScopedBookmarks: true }; const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.setSavePath(filePath); item.setSaveDialogOptions(options); item.on('done', function () { try { expect(item.getSaveDialogOptions()).to.deep.equal(options); done(); } catch (e) { done(e); } }); item.cancel(); }); w.webContents.downloadURL(`${url}:${port}`); }); describe('when a save path is specified and the URL is unavailable', () => { it('does not display a save dialog and reports the done state as interrupted', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) { item.savePath = downloadFilePath; if (item.getState() === 'interrupted') { item.resume(); } item.on('done', function (e, state) { try { expect(state).to.equal('interrupted'); done(); } catch (e) { done(e); } }); }); w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`); }); }); }); describe('ses.createInterruptedDownload(options)', () => { afterEach(closeAllWindows); it('can create an interrupted download item', async () => { const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf'); const options = { path: downloadFilePath, urlChain: ['http://127.0.0.1/'], mimeType: 'application/pdf', offset: 0, length: 5242880 }; const w = new BrowserWindow({ show: false }); const p = emittedOnce(w.webContents.session, 'will-download'); w.webContents.session.createInterruptedDownload(options); const [, item] = await p; expect(item.getState()).to.equal('interrupted'); item.cancel(); expect(item.getURLChain()).to.deep.equal(options.urlChain); expect(item.getMimeType()).to.equal(options.mimeType); expect(item.getReceivedBytes()).to.equal(options.offset); expect(item.getTotalBytes()).to.equal(options.length); expect(item.savePath).to.equal(downloadFilePath); }); it('can be resumed', async () => { const downloadFilePath = path.join(fixtures, 'logo.png'); const rangeServer = http.createServer((req, res) => { const options = { root: fixtures }; send(req, req.url!, options) .on('error', (error: any) => { throw error; }).pipe(res); }); try { await new Promise<void>(resolve => rangeServer.listen(0, '127.0.0.1', resolve)); const port = (rangeServer.address() as AddressInfo).port; const w = new BrowserWindow({ show: false }); const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => { w.webContents.session.once('will-download', function (e, item) { item.setSavePath(downloadFilePath); item.on('done', function () { resolve(item); }); item.cancel(); }); }); const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`; w.webContents.downloadURL(downloadUrl); const item = await downloadCancelled; expect(item.getState()).to.equal('cancelled'); const options = { path: item.savePath, urlChain: item.getURLChain(), mimeType: item.getMimeType(), offset: item.getReceivedBytes(), length: item.getTotalBytes(), lastModified: item.getLastModifiedTime(), eTag: item.getETag() }; const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => { w.webContents.session.once('will-download', function (e, item) { expect(item.getState()).to.equal('interrupted'); item.setSavePath(downloadFilePath); item.resume(); item.on('done', function () { resolve(item); }); }); }); w.webContents.session.createInterruptedDownload(options); const completedItem = await downloadResumed; expect(completedItem.getState()).to.equal('completed'); expect(completedItem.getFilename()).to.equal('logo.png'); expect(completedItem.savePath).to.equal(downloadFilePath); expect(completedItem.getURL()).to.equal(downloadUrl); expect(completedItem.getMimeType()).to.equal('image/png'); expect(completedItem.getReceivedBytes()).to.equal(14022); expect(completedItem.getTotalBytes()).to.equal(14022); expect(fs.existsSync(downloadFilePath)).to.equal(true); } finally { rangeServer.close(); } }); }); describe('ses.setPermissionRequestHandler(handler)', () => { afterEach(closeAllWindows); it('cancels any pending requests when cleared', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler', nodeIntegration: true, contextIsolation: false } }); const ses = w.webContents.session; ses.setPermissionRequestHandler(() => { ses.setPermissionRequestHandler(null); }); ses.protocol.interceptStringProtocol('https', (req, cb) => { cb(`<html><script>(${remote})()</script></html>`); }); const result = emittedOnce(require('electron').ipcMain, 'message'); function remote () { (navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => { require('electron').ipcRenderer.send('message', err.name); }); } await w.loadURL('https://myfakesite'); const [, name] = await result; expect(name).to.deep.equal('SecurityError'); }); }); describe('ses.setPermissionCheckHandler(handler)', () => { afterEach(closeAllWindows); it('details provides requestingURL for mainFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler' } }); const ses = w.webContents.session; const loadUrl = 'https://myfakesite/'; let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails; ses.protocol.interceptStringProtocol('https', (req, cb) => { cb('<html><script>console.log(\'test\');</script></html>'); }); ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => { if (permission === 'clipboard-read') { handlerDetails = details; return true; } return false; }); const readClipboardPermission: any = () => { return w.webContents.executeJavaScript(` navigator.permissions.query({name: 'clipboard-read'}) .then(permission => permission.state).catch(err => err.message); `, true); }; await w.loadURL(loadUrl); const state = await readClipboardPermission(); expect(state).to.equal('granted'); expect(handlerDetails!.requestingUrl).to.equal(loadUrl); }); it('details provides requestingURL for cross origin subFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'very-temp-permission-handler' } }); const ses = w.webContents.session; const loadUrl = 'https://myfakesite/'; let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails; ses.protocol.interceptStringProtocol('https', (req, cb) => { cb('<html><script>console.log(\'test\');</script></html>'); }); ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => { if (permission === 'clipboard-read') { handlerDetails = details; return true; } return false; }); const readClipboardPermission: any = (frame: WebFrameMain) => { return frame.executeJavaScript(` navigator.permissions.query({name: 'clipboard-read'}) .then(permission => permission.state).catch(err => err.message); `, true); }; await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe'); iframe.src = '${loadUrl}'; document.body.appendChild(iframe); null; `); const [,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-finish-load'); const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId)); expect(state).to.equal('granted'); expect(handlerDetails!.requestingUrl).to.equal(loadUrl); expect(handlerDetails!.isMainFrame).to.be.false(); expect(handlerDetails!.embeddingOrigin).to.equal('file:///'); }); }); describe('ses.isPersistent()', () => { afterEach(closeAllWindows); it('returns default session as persistent', () => { const w = new BrowserWindow({ show: false }); const ses = w.webContents.session; expect(ses.isPersistent()).to.be.true(); }); it('returns persist: session as persistent', () => { const ses = session.fromPartition(`persist:${Math.random()}`); expect(ses.isPersistent()).to.be.true(); }); it('returns temporary session as not persistent', () => { const ses = session.fromPartition(`${Math.random()}`); expect(ses.isPersistent()).to.be.false(); }); }); describe('ses.setUserAgent()', () => { afterEach(closeAllWindows); it('can be retrieved with getUserAgent()', () => { const userAgent = 'test-agent'; const ses = session.fromPartition('' + Math.random()); ses.setUserAgent(userAgent); expect(ses.getUserAgent()).to.equal(userAgent); }); it('sets the User-Agent header for web requests made from renderers', async () => { const userAgent = 'test-agent'; const ses = session.fromPartition('' + Math.random()); ses.setUserAgent(userAgent, 'en-US,fr,de'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); let headers: http.IncomingHttpHeaders | null = null; const server = http.createServer((req, res) => { headers = req.headers; res.end(); server.close(); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); expect(headers!['user-agent']).to.equal(userAgent); expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8'); }); }); describe('session-created event', () => { it('is emitted when a session is created', async () => { const sessionCreated = emittedOnce(app, 'session-created'); const session1 = session.fromPartition('' + Math.random()); const [session2] = await sessionCreated; expect(session1).to.equal(session2); }); }); describe('session.storagePage', () => { it('returns a string', () => { expect(session.defaultSession.storagePath).to.be.a('string'); }); it('returns null for in memory sessions', () => { expect(session.fromPartition('in-memory').storagePath).to.equal(null); }); it('returns different paths for partitions and the default session', () => { expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath); }); it('returns different paths for different partitions', () => { expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath); }); }); describe('session.setCodeCachePath()', () => { it('throws when relative or empty path is provided', () => { expect(() => { session.defaultSession.setCodeCachePath('../fixtures'); }).to.throw('Absolute path must be provided to store code cache.'); expect(() => { session.defaultSession.setCodeCachePath(''); }).to.throw('Absolute path must be provided to store code cache.'); expect(() => { session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache')); }).to.not.throw(); }); }); describe('ses.setSSLConfig()', () => { it('can disable cipher suites', async () => { const ses = session.fromPartition('' + Math.random()); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); const server = https.createServer({ key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], minVersion: 'TLSv1.2', maxVersion: 'TLSv1.2', ciphers: 'AES128-GCM-SHA256' }, (req, res) => { res.end('hi'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); defer(() => server.close()); const { port } = server.address() as AddressInfo; function request () { return new Promise((resolve, reject) => { const r = net.request({ url: `https://127.0.0.1:${port}`, session: ses }); r.on('response', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk.toString('utf8'); }); res.on('end', () => { resolve(data); }); }); r.on('error', (err) => { reject(err); }); r.end(); }); } await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/); ses.setSSLConfig({ disabledCipherSuites: [0x009C] }); await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/); }); }); });
closed
electron/electron
https://github.com/electron/electron
35,312
[Bug]: WCO separator colour incorrect in v20
Alright, I guess I wasn't running it in the right electron version, but with fiddle it also is off-center. This issue doesn't appear in v20.0.0, but in v20, the WCO just looks weird. Maybe that bug occurs only with some specific settings, I'll look into it later. This is what I mean by "weird": ![screenshot](https://user-images.githubusercontent.com/90904039/182640528-d0d5e3fa-3180-4254-8cd7-4e67a699ea64.png) ![screenshot](https://user-images.githubusercontent.com/90904039/182640532-2054adeb-9596-4990-8c04-c1ff15535ee7.png) _Originally posted by @wheezard in https://github.com/electron/electron/issues/35038#issuecomment-1204061897_
https://github.com/electron/electron/issues/35312
https://github.com/electron/electron/pull/35569
17d501616368e2a0c709cbc2174de38e1781e8c3
4fb4167b8b42276710b658a3c62f0ebe9fffe446
2022-08-11T16:12:49Z
c++
2022-09-08T13:11:51Z
shell/browser/ui/views/win_caption_button_container.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc #include "shell/browser/ui/views/win_caption_button_container.h" #include <memory> #include <utility> #include "shell/browser/ui/views/win_caption_button.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/l10n/l10n_util.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" namespace electron { namespace { std::unique_ptr<WinCaptionButton> CreateCaptionButton( views::Button::PressedCallback callback, WinFrameView* frame_view, ViewID button_type, int accessible_name_resource_id) { return std::make_unique<WinCaptionButton>( std::move(callback), frame_view, button_type, l10n_util::GetStringUTF16(accessible_name_resource_id)); } bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) { return button && button->GetVisible() && button->bounds().Contains(point); } } // anonymous namespace WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view) : frame_view_(frame_view), minimize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Minimize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MINIMIZE_BUTTON, IDS_APP_ACCNAME_MINIMIZE))), maximize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Maximize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MAXIMIZE_BUTTON, IDS_APP_ACCNAME_MAXIMIZE))), restore_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Restore, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_RESTORE_BUTTON, IDS_APP_ACCNAME_RESTORE))), close_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::CloseWithReason, base::Unretained(frame_view_->frame()), views::Widget::ClosedReason::kCloseButtonClicked), frame_view_, VIEW_ID_CLOSE_BUTTON, IDS_APP_ACCNAME_CLOSE))) { // Layout is horizontal, with buttons placed at the trailing end of the view. // This allows the container to expand to become a faux titlebar/drag handle. auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kEnd) .SetCrossAxisAlignment(views::LayoutAlignment::kStart) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kPreferred, /* adjust_width_for_height */ false, views::MinimumFlexSizeRule::kScaleToZero)); } WinCaptionButtonContainer::~WinCaptionButtonContainer() {} int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const { DCHECK(HitTestPoint(point)) << "should only be called with a point inside this view's bounds"; if (HitTestCaptionButton(minimize_button_, point)) { return HTMINBUTTON; } if (HitTestCaptionButton(maximize_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(restore_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(close_button_, point)) { return HTCLOSE; } return HTCAPTION; } gfx::Size WinCaptionButtonContainer::GetButtonSize() const { // Close button size is set the same as all the buttons return close_button_->GetSize(); } void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) { minimize_button_->SetSize(size); maximize_button_->SetSize(size); restore_button_->SetSize(size); close_button_->SetSize(size); } void WinCaptionButtonContainer::ResetWindowControls() { minimize_button_->SetState(views::Button::STATE_NORMAL); maximize_button_->SetState(views::Button::STATE_NORMAL); restore_button_->SetState(views::Button::STATE_NORMAL); close_button_->SetState(views::Button::STATE_NORMAL); InvalidateLayout(); } void WinCaptionButtonContainer::AddedToWidget() { views::Widget* const widget = GetWidget(); DCHECK(!widget_observation_.IsObserving()); widget_observation_.Observe(widget); UpdateButtons(); if (frame_view_->window()->IsWindowControlsOverlayEnabled()) { SetPaintToLayer(); } } void WinCaptionButtonContainer::RemovedFromWidget() { DCHECK(widget_observation_.IsObserving()); widget_observation_.Reset(); } void WinCaptionButtonContainer::OnWidgetBoundsChanged( views::Widget* widget, const gfx::Rect& new_bounds) { UpdateButtons(); } void WinCaptionButtonContainer::UpdateButtons() { const bool is_maximized = frame_view_->frame()->IsMaximized(); restore_button_->SetVisible(is_maximized); maximize_button_->SetVisible(!is_maximized); const bool minimizable = frame_view_->window()->IsMinimizable(); minimize_button_->SetEnabled(minimizable); // In touch mode, windows cannot be taken out of fullscreen or tiled mode, so // the maximize/restore button should be disabled. const bool is_touch = ui::TouchUiController::Get()->touch_ui(); restore_button_->SetEnabled(!is_touch); // The maximize button should only be enabled if the window is // maximizable *and* touch mode is disabled. const bool maximizable = frame_view_->window()->IsMaximizable(); maximize_button_->SetEnabled(!is_touch && maximizable); const bool closable = frame_view_->window()->IsClosable(); close_button_->SetEnabled(closable); // If all three of closable, maximizable, and minimizable are disabled, // Windows natively only shows the disabled closable button. Copy that // behavior here. if (!maximizable && !closable && !minimizable) { minimize_button_->SetVisible(false); maximize_button_->SetVisible(false); } InvalidateLayout(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,312
[Bug]: WCO separator colour incorrect in v20
Alright, I guess I wasn't running it in the right electron version, but with fiddle it also is off-center. This issue doesn't appear in v20.0.0, but in v20, the WCO just looks weird. Maybe that bug occurs only with some specific settings, I'll look into it later. This is what I mean by "weird": ![screenshot](https://user-images.githubusercontent.com/90904039/182640528-d0d5e3fa-3180-4254-8cd7-4e67a699ea64.png) ![screenshot](https://user-images.githubusercontent.com/90904039/182640532-2054adeb-9596-4990-8c04-c1ff15535ee7.png) _Originally posted by @wheezard in https://github.com/electron/electron/issues/35038#issuecomment-1204061897_
https://github.com/electron/electron/issues/35312
https://github.com/electron/electron/pull/35569
17d501616368e2a0c709cbc2174de38e1781e8c3
4fb4167b8b42276710b658a3c62f0ebe9fffe446
2022-08-11T16:12:49Z
c++
2022-09-08T13:11:51Z
shell/browser/ui/views/win_frame_view.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.cc, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #include "shell/browser/ui/views/win_frame_view.h" #include <dwmapi.h> #include <memory> #include "base/win/windows_version.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/win_caption_button_container.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/display/win/dpi.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/views/widget/widget.h" #include "ui/views/win/hwnd_util.h" namespace electron { const char WinFrameView::kViewClassName[] = "WinFrameView"; WinFrameView::WinFrameView() = default; WinFrameView::~WinFrameView() = default; void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) { window_ = window; frame_ = frame; if (window->IsWindowControlsOverlayEnabled()) { caption_button_container_ = AddChildView(std::make_unique<WinCaptionButtonContainer>(this)); } else { caption_button_container_ = nullptr; } } SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) { // color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because // they switch based on the Chrome light/dark endpoints, while we want to use // the system native behavior below. const auto windows_luma = [](SkColor c) { return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) + 0.125f * SkColorGetB(c); }; return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE : SK_ColorBLACK; } void WinFrameView::InvalidateCaptionButtons() { if (!caption_button_container_) return; caption_button_container_->InvalidateLayout(); caption_button_container_->SchedulePaint(); } gfx::Rect WinFrameView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { return views::GetWindowBoundsForClientBounds( static_cast<views::View*>(const_cast<WinFrameView*>(this)), client_bounds); } int WinFrameView::FrameBorderThickness() const { return (IsMaximized() || frame()->IsFullscreen()) ? 0 : display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME); } views::View* WinFrameView::TargetForRect(views::View* root, const gfx::Rect& rect) { if (NonClientHitTest(rect.origin()) != HTCLIENT) { // Custom system titlebar returns non HTCLIENT value, however event should // be handled by the view, not by the system, because there are no system // buttons underneath. if (!ShouldCustomDrawSystemTitlebar()) { return this; } auto local_point = rect.origin(); ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (!caption_button_container_->HitTestPoint(local_point)) { return this; } } return NonClientFrameView::TargetForRect(root, rect); } int WinFrameView::NonClientHitTest(const gfx::Point& point) { if (window_->has_frame()) return frame_->client_view()->NonClientHitTest(point); if (ShouldCustomDrawSystemTitlebar()) { // See if the point is within any of the window controls. if (caption_button_container_) { gfx::Point local_point = point; ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (caption_button_container_->HitTestPoint(local_point)) { const int hit_test_result = caption_button_container_->NonClientHitTest(local_point); if (hit_test_result != HTNOWHERE) return hit_test_result; } } // On Windows 8+, the caption buttons are almost butted up to the top right // corner of the window. This code ensures the mouse isn't set to a size // cursor while hovering over the caption buttons, thus giving the incorrect // impression that the user can resize the window. if (base::win::GetVersion() >= base::win::Version::WIN8) { RECT button_bounds = {0}; if (SUCCEEDED(DwmGetWindowAttribute( views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS, &button_bounds, sizeof(button_bounds)))) { gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips( gfx::Rect(button_bounds), display::win::GetDPIScale()); // TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect, // but the size in DIPs may not be an integer with a fractional device // scale factor. If we want to keep using integers, the choice to use // ToFlooredRectDeprecated() seems to be doing the wrong thing given the // comment below about insetting 1 DIP instead of 1 physical pixel. We // should probably use ToEnclosedRect() and then we could have inset 1 // physical pixel here. gfx::Rect buttons = GetMirroredRect( gfx::ToFlooredRectDeprecated(button_bounds_in_dips)); // There is a small one-pixel strip right above the caption buttons in // which the resize border "peeks" through. constexpr int kCaptionButtonTopInset = 1; // The sizing region at the window edge above the caption buttons is // 1 px regardless of scale factor. If we inset by 1 before converting // to DIPs, the precision loss might eliminate this region entirely. The // best we can do is to inset after conversion. This guarantees we'll // show the resize cursor when resizing is possible. The cost of which // is also maybe showing it over the portion of the DIP that isn't the // outermost pixel. buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0)); if (buttons.Contains(point)) return HTNOWHERE; } } int top_border_thickness = FrameTopBorderThickness(false); // At the window corners the resize area is not actually bigger, but the 16 // pixels at the end of the top and bottom edges trigger diagonal resizing. constexpr int kResizeCornerWidth = 16; int window_component = GetHTComponentForFrame( point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0), top_border_thickness, kResizeCornerWidth - FrameBorderThickness(), frame()->widget_delegate()->CanResize()); if (window_component != HTNOWHERE) return window_component; } // Use the parent class's hittest last return FramelessView::NonClientHitTest(point); } const char* WinFrameView::GetClassName() const { return kViewClassName; } bool WinFrameView::IsMaximized() const { return frame()->IsMaximized(); } bool WinFrameView::ShouldCustomDrawSystemTitlebar() const { return window()->IsWindowControlsOverlayEnabled(); } void WinFrameView::Layout() { LayoutCaptionButtons(); if (window()->IsWindowControlsOverlayEnabled()) { LayoutWindowControlsOverlay(); } NonClientFrameView::Layout(); } int WinFrameView::FrameTopBorderThickness(bool restored) const { // Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded, // so we need to floor instead or else the difference will cause the hittest // to fail when it ought to succeed. return std::floor( FrameTopBorderThicknessPx(restored) / display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this))); } int WinFrameView::FrameTopBorderThicknessPx(bool restored) const { // Distinct from FrameBorderThickness() because we can't inset the top // border, otherwise Windows will give us a standard titlebar. // For maximized windows this is not true, and the top border must be // inset in order to avoid overlapping the monitor above. // See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets(). const bool needs_no_border = (ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) || frame()->IsFullscreen(); if (needs_no_border && !restored) return 0; // Note that this method assumes an equal resize handle thickness on all // sides of the window. // TODO(dfried): Consider having it return a gfx::Insets object instead. return ui::GetFrameThickness( MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST)); } int WinFrameView::TitlebarMaximizedVisualHeight() const { int maximized_height = display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION); return maximized_height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::TitlebarHeight(int custom_height) const { if (frame()->IsFullscreen() && !IsMaximized()) return 0; int height = TitlebarMaximizedVisualHeight() + FrameTopBorderThickness(false) - WindowTopY(); if (custom_height > TitlebarMaximizedVisualHeight()) height = custom_height - WindowTopY(); return height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::WindowTopY() const { // The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in // FrameTopBorderThickness()) and floor(system dsf) pixels when restored. // Unfortunately we can't represent either of those at hidpi without using // non-integral dips, so we return the closest reasonable values instead. if (IsMaximized()) return FrameTopBorderThickness(false); return 1; } void WinFrameView::LayoutCaptionButtons() { if (!caption_button_container_) return; // Non-custom system titlebar already contains caption buttons. if (!ShouldCustomDrawSystemTitlebar()) { caption_button_container_->SetVisible(false); return; } caption_button_container_->SetVisible(true); const gfx::Size preferred_size = caption_button_container_->GetPreferredSize(); int custom_height = window()->titlebar_overlay_height(); int height = TitlebarHeight(custom_height); // TODO(mlaurencin): This -1 creates a 1 pixel margin between the right // edge of the button container and the edge of the window, allowing for this // edge portion to return the correct hit test and be manually resized // properly. Alternatives can be explored, but the differences in view // structures between Electron and Chromium may result in this as the best // option. int variable_width = IsMaximized() ? preferred_size.width() : preferred_size.width() - 1; caption_button_container_->SetBounds(width() - preferred_size.width(), WindowTopY(), variable_width, height); // Needed for heights larger than default caption_button_container_->SetButtonSize(gfx::Size(0, height)); } void WinFrameView::LayoutWindowControlsOverlay() { int overlay_height = window()->titlebar_overlay_height(); if (overlay_height == 0) { // Accounting for the 1 pixel margin at the top of the button container overlay_height = IsMaximized() ? caption_button_container_->size().height() : caption_button_container_->size().height() + 1; } int overlay_width = caption_button_container_->size().width(); int bounding_rect_width = width() - overlay_width; auto bounding_rect = GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height)); window()->SetWindowControlsOverlayRect(bounding_rect); window()->NotifyLayoutWindowControlsOverlay(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,312
[Bug]: WCO separator colour incorrect in v20
Alright, I guess I wasn't running it in the right electron version, but with fiddle it also is off-center. This issue doesn't appear in v20.0.0, but in v20, the WCO just looks weird. Maybe that bug occurs only with some specific settings, I'll look into it later. This is what I mean by "weird": ![screenshot](https://user-images.githubusercontent.com/90904039/182640528-d0d5e3fa-3180-4254-8cd7-4e67a699ea64.png) ![screenshot](https://user-images.githubusercontent.com/90904039/182640532-2054adeb-9596-4990-8c04-c1ff15535ee7.png) _Originally posted by @wheezard in https://github.com/electron/electron/issues/35038#issuecomment-1204061897_
https://github.com/electron/electron/issues/35312
https://github.com/electron/electron/pull/35569
17d501616368e2a0c709cbc2174de38e1781e8c3
4fb4167b8b42276710b658a3c62f0ebe9fffe446
2022-08-11T16:12:49Z
c++
2022-09-08T13:11:51Z
shell/browser/ui/views/win_caption_button_container.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc #include "shell/browser/ui/views/win_caption_button_container.h" #include <memory> #include <utility> #include "shell/browser/ui/views/win_caption_button.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/l10n/l10n_util.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" namespace electron { namespace { std::unique_ptr<WinCaptionButton> CreateCaptionButton( views::Button::PressedCallback callback, WinFrameView* frame_view, ViewID button_type, int accessible_name_resource_id) { return std::make_unique<WinCaptionButton>( std::move(callback), frame_view, button_type, l10n_util::GetStringUTF16(accessible_name_resource_id)); } bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) { return button && button->GetVisible() && button->bounds().Contains(point); } } // anonymous namespace WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view) : frame_view_(frame_view), minimize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Minimize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MINIMIZE_BUTTON, IDS_APP_ACCNAME_MINIMIZE))), maximize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Maximize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MAXIMIZE_BUTTON, IDS_APP_ACCNAME_MAXIMIZE))), restore_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Restore, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_RESTORE_BUTTON, IDS_APP_ACCNAME_RESTORE))), close_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::CloseWithReason, base::Unretained(frame_view_->frame()), views::Widget::ClosedReason::kCloseButtonClicked), frame_view_, VIEW_ID_CLOSE_BUTTON, IDS_APP_ACCNAME_CLOSE))) { // Layout is horizontal, with buttons placed at the trailing end of the view. // This allows the container to expand to become a faux titlebar/drag handle. auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kEnd) .SetCrossAxisAlignment(views::LayoutAlignment::kStart) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kPreferred, /* adjust_width_for_height */ false, views::MinimumFlexSizeRule::kScaleToZero)); } WinCaptionButtonContainer::~WinCaptionButtonContainer() {} int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const { DCHECK(HitTestPoint(point)) << "should only be called with a point inside this view's bounds"; if (HitTestCaptionButton(minimize_button_, point)) { return HTMINBUTTON; } if (HitTestCaptionButton(maximize_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(restore_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(close_button_, point)) { return HTCLOSE; } return HTCAPTION; } gfx::Size WinCaptionButtonContainer::GetButtonSize() const { // Close button size is set the same as all the buttons return close_button_->GetSize(); } void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) { minimize_button_->SetSize(size); maximize_button_->SetSize(size); restore_button_->SetSize(size); close_button_->SetSize(size); } void WinCaptionButtonContainer::ResetWindowControls() { minimize_button_->SetState(views::Button::STATE_NORMAL); maximize_button_->SetState(views::Button::STATE_NORMAL); restore_button_->SetState(views::Button::STATE_NORMAL); close_button_->SetState(views::Button::STATE_NORMAL); InvalidateLayout(); } void WinCaptionButtonContainer::AddedToWidget() { views::Widget* const widget = GetWidget(); DCHECK(!widget_observation_.IsObserving()); widget_observation_.Observe(widget); UpdateButtons(); if (frame_view_->window()->IsWindowControlsOverlayEnabled()) { SetPaintToLayer(); } } void WinCaptionButtonContainer::RemovedFromWidget() { DCHECK(widget_observation_.IsObserving()); widget_observation_.Reset(); } void WinCaptionButtonContainer::OnWidgetBoundsChanged( views::Widget* widget, const gfx::Rect& new_bounds) { UpdateButtons(); } void WinCaptionButtonContainer::UpdateButtons() { const bool is_maximized = frame_view_->frame()->IsMaximized(); restore_button_->SetVisible(is_maximized); maximize_button_->SetVisible(!is_maximized); const bool minimizable = frame_view_->window()->IsMinimizable(); minimize_button_->SetEnabled(minimizable); // In touch mode, windows cannot be taken out of fullscreen or tiled mode, so // the maximize/restore button should be disabled. const bool is_touch = ui::TouchUiController::Get()->touch_ui(); restore_button_->SetEnabled(!is_touch); // The maximize button should only be enabled if the window is // maximizable *and* touch mode is disabled. const bool maximizable = frame_view_->window()->IsMaximizable(); maximize_button_->SetEnabled(!is_touch && maximizable); const bool closable = frame_view_->window()->IsClosable(); close_button_->SetEnabled(closable); // If all three of closable, maximizable, and minimizable are disabled, // Windows natively only shows the disabled closable button. Copy that // behavior here. if (!maximizable && !closable && !minimizable) { minimize_button_->SetVisible(false); maximize_button_->SetVisible(false); } InvalidateLayout(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,312
[Bug]: WCO separator colour incorrect in v20
Alright, I guess I wasn't running it in the right electron version, but with fiddle it also is off-center. This issue doesn't appear in v20.0.0, but in v20, the WCO just looks weird. Maybe that bug occurs only with some specific settings, I'll look into it later. This is what I mean by "weird": ![screenshot](https://user-images.githubusercontent.com/90904039/182640528-d0d5e3fa-3180-4254-8cd7-4e67a699ea64.png) ![screenshot](https://user-images.githubusercontent.com/90904039/182640532-2054adeb-9596-4990-8c04-c1ff15535ee7.png) _Originally posted by @wheezard in https://github.com/electron/electron/issues/35038#issuecomment-1204061897_
https://github.com/electron/electron/issues/35312
https://github.com/electron/electron/pull/35569
17d501616368e2a0c709cbc2174de38e1781e8c3
4fb4167b8b42276710b658a3c62f0ebe9fffe446
2022-08-11T16:12:49Z
c++
2022-09-08T13:11:51Z
shell/browser/ui/views/win_frame_view.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.cc, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #include "shell/browser/ui/views/win_frame_view.h" #include <dwmapi.h> #include <memory> #include "base/win/windows_version.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/win_caption_button_container.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/display/win/dpi.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/views/widget/widget.h" #include "ui/views/win/hwnd_util.h" namespace electron { const char WinFrameView::kViewClassName[] = "WinFrameView"; WinFrameView::WinFrameView() = default; WinFrameView::~WinFrameView() = default; void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) { window_ = window; frame_ = frame; if (window->IsWindowControlsOverlayEnabled()) { caption_button_container_ = AddChildView(std::make_unique<WinCaptionButtonContainer>(this)); } else { caption_button_container_ = nullptr; } } SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) { // color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because // they switch based on the Chrome light/dark endpoints, while we want to use // the system native behavior below. const auto windows_luma = [](SkColor c) { return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) + 0.125f * SkColorGetB(c); }; return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE : SK_ColorBLACK; } void WinFrameView::InvalidateCaptionButtons() { if (!caption_button_container_) return; caption_button_container_->InvalidateLayout(); caption_button_container_->SchedulePaint(); } gfx::Rect WinFrameView::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { return views::GetWindowBoundsForClientBounds( static_cast<views::View*>(const_cast<WinFrameView*>(this)), client_bounds); } int WinFrameView::FrameBorderThickness() const { return (IsMaximized() || frame()->IsFullscreen()) ? 0 : display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME); } views::View* WinFrameView::TargetForRect(views::View* root, const gfx::Rect& rect) { if (NonClientHitTest(rect.origin()) != HTCLIENT) { // Custom system titlebar returns non HTCLIENT value, however event should // be handled by the view, not by the system, because there are no system // buttons underneath. if (!ShouldCustomDrawSystemTitlebar()) { return this; } auto local_point = rect.origin(); ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (!caption_button_container_->HitTestPoint(local_point)) { return this; } } return NonClientFrameView::TargetForRect(root, rect); } int WinFrameView::NonClientHitTest(const gfx::Point& point) { if (window_->has_frame()) return frame_->client_view()->NonClientHitTest(point); if (ShouldCustomDrawSystemTitlebar()) { // See if the point is within any of the window controls. if (caption_button_container_) { gfx::Point local_point = point; ConvertPointToTarget(parent(), caption_button_container_, &local_point); if (caption_button_container_->HitTestPoint(local_point)) { const int hit_test_result = caption_button_container_->NonClientHitTest(local_point); if (hit_test_result != HTNOWHERE) return hit_test_result; } } // On Windows 8+, the caption buttons are almost butted up to the top right // corner of the window. This code ensures the mouse isn't set to a size // cursor while hovering over the caption buttons, thus giving the incorrect // impression that the user can resize the window. if (base::win::GetVersion() >= base::win::Version::WIN8) { RECT button_bounds = {0}; if (SUCCEEDED(DwmGetWindowAttribute( views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS, &button_bounds, sizeof(button_bounds)))) { gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips( gfx::Rect(button_bounds), display::win::GetDPIScale()); // TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect, // but the size in DIPs may not be an integer with a fractional device // scale factor. If we want to keep using integers, the choice to use // ToFlooredRectDeprecated() seems to be doing the wrong thing given the // comment below about insetting 1 DIP instead of 1 physical pixel. We // should probably use ToEnclosedRect() and then we could have inset 1 // physical pixel here. gfx::Rect buttons = GetMirroredRect( gfx::ToFlooredRectDeprecated(button_bounds_in_dips)); // There is a small one-pixel strip right above the caption buttons in // which the resize border "peeks" through. constexpr int kCaptionButtonTopInset = 1; // The sizing region at the window edge above the caption buttons is // 1 px regardless of scale factor. If we inset by 1 before converting // to DIPs, the precision loss might eliminate this region entirely. The // best we can do is to inset after conversion. This guarantees we'll // show the resize cursor when resizing is possible. The cost of which // is also maybe showing it over the portion of the DIP that isn't the // outermost pixel. buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0)); if (buttons.Contains(point)) return HTNOWHERE; } } int top_border_thickness = FrameTopBorderThickness(false); // At the window corners the resize area is not actually bigger, but the 16 // pixels at the end of the top and bottom edges trigger diagonal resizing. constexpr int kResizeCornerWidth = 16; int window_component = GetHTComponentForFrame( point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0), top_border_thickness, kResizeCornerWidth - FrameBorderThickness(), frame()->widget_delegate()->CanResize()); if (window_component != HTNOWHERE) return window_component; } // Use the parent class's hittest last return FramelessView::NonClientHitTest(point); } const char* WinFrameView::GetClassName() const { return kViewClassName; } bool WinFrameView::IsMaximized() const { return frame()->IsMaximized(); } bool WinFrameView::ShouldCustomDrawSystemTitlebar() const { return window()->IsWindowControlsOverlayEnabled(); } void WinFrameView::Layout() { LayoutCaptionButtons(); if (window()->IsWindowControlsOverlayEnabled()) { LayoutWindowControlsOverlay(); } NonClientFrameView::Layout(); } int WinFrameView::FrameTopBorderThickness(bool restored) const { // Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded, // so we need to floor instead or else the difference will cause the hittest // to fail when it ought to succeed. return std::floor( FrameTopBorderThicknessPx(restored) / display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this))); } int WinFrameView::FrameTopBorderThicknessPx(bool restored) const { // Distinct from FrameBorderThickness() because we can't inset the top // border, otherwise Windows will give us a standard titlebar. // For maximized windows this is not true, and the top border must be // inset in order to avoid overlapping the monitor above. // See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets(). const bool needs_no_border = (ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) || frame()->IsFullscreen(); if (needs_no_border && !restored) return 0; // Note that this method assumes an equal resize handle thickness on all // sides of the window. // TODO(dfried): Consider having it return a gfx::Insets object instead. return ui::GetFrameThickness( MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST)); } int WinFrameView::TitlebarMaximizedVisualHeight() const { int maximized_height = display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION); return maximized_height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::TitlebarHeight(int custom_height) const { if (frame()->IsFullscreen() && !IsMaximized()) return 0; int height = TitlebarMaximizedVisualHeight() + FrameTopBorderThickness(false) - WindowTopY(); if (custom_height > TitlebarMaximizedVisualHeight()) height = custom_height - WindowTopY(); return height; } // NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium int WinFrameView::WindowTopY() const { // The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in // FrameTopBorderThickness()) and floor(system dsf) pixels when restored. // Unfortunately we can't represent either of those at hidpi without using // non-integral dips, so we return the closest reasonable values instead. if (IsMaximized()) return FrameTopBorderThickness(false); return 1; } void WinFrameView::LayoutCaptionButtons() { if (!caption_button_container_) return; // Non-custom system titlebar already contains caption buttons. if (!ShouldCustomDrawSystemTitlebar()) { caption_button_container_->SetVisible(false); return; } caption_button_container_->SetVisible(true); const gfx::Size preferred_size = caption_button_container_->GetPreferredSize(); int custom_height = window()->titlebar_overlay_height(); int height = TitlebarHeight(custom_height); // TODO(mlaurencin): This -1 creates a 1 pixel margin between the right // edge of the button container and the edge of the window, allowing for this // edge portion to return the correct hit test and be manually resized // properly. Alternatives can be explored, but the differences in view // structures between Electron and Chromium may result in this as the best // option. int variable_width = IsMaximized() ? preferred_size.width() : preferred_size.width() - 1; caption_button_container_->SetBounds(width() - preferred_size.width(), WindowTopY(), variable_width, height); // Needed for heights larger than default caption_button_container_->SetButtonSize(gfx::Size(0, height)); } void WinFrameView::LayoutWindowControlsOverlay() { int overlay_height = window()->titlebar_overlay_height(); if (overlay_height == 0) { // Accounting for the 1 pixel margin at the top of the button container overlay_height = IsMaximized() ? caption_button_container_->size().height() : caption_button_container_->size().height() + 1; } int overlay_width = caption_button_container_->size().width(); int bounding_rect_width = width() - overlay_width; auto bounding_rect = GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height)); window()->SetWindowControlsOverlayRect(bounding_rect); window()->NotifyLayoutWindowControlsOverlay(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
shell/browser/api/electron_api_web_contents.cc
// 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/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/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.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/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.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/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/result_codes.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/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.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/file_select_helper.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_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.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 !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #include "shell/browser/native_window_views.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::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 BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(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 BUILDFLAG(IS_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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_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 if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), 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 !BUILDFLAG(IS_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 BUILDFLAG(IS_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().DeprecatedGetOriginAsURL(); 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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = 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(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // 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::kOffscreenDocument: 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; 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()); InitWithWebContents(std::move(owned_web_contents), 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 BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(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); // 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::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&WebContents::DeleteThisIfAlive, 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; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(requesting_frame, callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } #if BUILDFLAG(IS_WIN) auto* win = static_cast<NativeWindowViews*>(owner_window()); // Force a detached state when WCO is enabled to match Chrome // behavior and prevent occlusion of DevTools. if (win && win->IsWindowControlsOverlayEnabled()) state = "detach"; #endif DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDeviceNameToUse(base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings); void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void 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); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; bool OnGoToEntryOffset(int offset) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import * as https from 'https'; import * as http from 'http'; import * as path from 'path'; import * as fs from 'fs'; import * as url from 'url'; import * as ChildProcess from 'child_process'; import { EventEmitter } from 'events'; import { promisify } from 'util'; import { ifit, ifdescribe, defer, delay, itremote } from './spec-helpers'; import { AddressInfo } from 'net'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); describe('reporting api', () => { // TODO(nornagon): this started failing a lot on CI. Figure out why and fix // it. it.skip('sends a report for a deprecation', async () => { const reports = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const certPath = path.join(fixturesPath, 'certificates'); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url === '/report') { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reports.emit('report', JSON.parse(data)); }); } res.setHeader('Report-To', JSON.stringify({ group: 'default', max_age: 120, endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }] })); res.setHeader('Content-Type', 'text/html'); // using the deprecated `webkitRequestAnimationFrame` will trigger a // "deprecation" report. res.end('<script>webkitRequestAnimationFrame(() => {})</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = emittedOnce(reports, 'report'); const url = `https://localhost:${(server.address() as any).port}/a`; await bw.loadURL(url); const [report] = await reportGenerated; expect(report).to.be.an('array'); expect(report[0].type).to.equal('deprecation'); expect(report[0].url).to.equal(url); expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame'); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await emittedOnce(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents = null as unknown as WebContents; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = emittedOnce(w.webContents, 'did-attach-webview'); await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await emittedOnce(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', 'fr')); it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await new Promise(resolve => { appProcess!.on('exit', resolve); }); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await emittedOnce(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await emittedOnce(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not crash when nodeIntegration is enabled', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); }); ifdescribe(features.isFakeLocationProviderEnabled())('navigator.geolocation', () => { it('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = emittedOnce(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); it('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), reject))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await emittedOnce(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/shared_worker.html`); const [, data] = await emittedOnce(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = emittedOnce(app, 'browser-window-created'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = emittedOnce(app, 'browser-window-created'); w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await emittedOnce(app, 'browser-window-created'); const preferences = window.webContents.getLastWebPreferences(); expect(preferences.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await emittedOnce(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await emittedOnce(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); // TODO(nornagon): I'm not sure this ... ever was correct? it.skip('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach((done) => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); server.listen(0, '127.0.0.1', () => { serverURL = `http://127.0.0.1:${server.address().port}`; done(); }); }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds'); const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload()); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload()); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))'); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { (contents as any).destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = emittedOnce(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = emittedOnce(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = emittedOnce(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = emittedOnce(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = emittedOnce(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('crashed', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { (contents as any).destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await delay(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await emittedOnce(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); ifdescribe(process.platform !== 'win32' && process.platform !== 'linux')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); ifdescribe(features.isTtsEnabled())('SpeechSynthesis', () => { before(function () { // TODO(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). this.skip(); }); itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow, server: http.Server; before(() => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); server.listen(8989, '127.0.0.1'); }); beforeEach(() => { w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); const html = '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>'; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await delay(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await emittedOnce(w, 'enter-full-screen'); const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); const html = '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>'; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await emittedOnce(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await emittedOnce(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await emittedOnce(w, 'enter-full-screen'); const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal('NotFoundError: No port selected by the user.'); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); }); describe('navigator.clipboard', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ webPreferences: { enableBlinkFeatures: 'Serial' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await new Promise(resolve => setTimeout(resolve, 10)); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (process.arch === 'arm64' || process.arch === 'arm') { // arm CI returns HID devices - this block may need to change if CI hardware changes. expect(haveDevices).to.be.true(); // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.empty(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
shell/browser/api/electron_api_web_contents.cc
// 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/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/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.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/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.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/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/result_codes.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/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.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/file_select_helper.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_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.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 !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #include "shell/browser/native_window_views.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::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 BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(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 BUILDFLAG(IS_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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_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 if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), 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 !BUILDFLAG(IS_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 BUILDFLAG(IS_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().DeprecatedGetOriginAsURL(); 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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = 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(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // 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::kOffscreenDocument: 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; 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()); InitWithWebContents(std::move(owned_web_contents), 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 BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(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); // 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::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&WebContents::DeleteThisIfAlive, 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; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(requesting_frame, callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } #if BUILDFLAG(IS_WIN) auto* win = static_cast<NativeWindowViews*>(owner_window()); // Force a detached state when WCO is enabled to match Chrome // behavior and prevent occlusion of DevTools. if (win && win->IsWindowControlsOverlayEnabled()) state = "detach"; #endif DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDeviceNameToUse(base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings); void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void 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); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; bool OnGoToEntryOffset(int offset) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
35,391
[Bug]: sandboxed iframe can modify history of parent browsing context
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3, same behavior going back to 17.0.0 ### What operating system are you using? macOS ### Operating System Version macOS 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior I expect that calling `history.back()` from a sandboxed iframe should do nothing, which is the behavior in Chrome 104.0.5112.101. ### Actual Behavior Create three .html files: page1.html: ``` <html> <body> Page 1 <a href="/page2.html">Go to Page 2</a> </body> </html> ``` page2.html: ``` <html> <body> Page 2 <iframe src="page_iframe.html" sandbox="allow-scripts"></iframe> </body> </html> ``` page_iframe.html: ``` <html> <body> <button onclick="history.back()">Go Back</button> </body> </html> ``` Serve them: ``` npx http-server . ``` Load page 1 in Electron: ``` mainWindow.loadURL('http://localhost:8080/page1.html') ``` and click the link to page2.html. Then click the `Go Back` button that is shown in the iframe on Page 2 and notice that the window is navigated back to page1.html. ### Testcase Gist URL https://gist.github.com/7d7b3f33d4a6283e9e3cc000da2ab6f9 ### Additional Information This was previously reported in https://github.com/electron/electron/issues/3734 and https://github.com/electron/electron/issues/21680 but not with a reproducible case.
https://github.com/electron/electron/issues/35391
https://github.com/electron/electron/pull/35420
b0036ea43afda71e33c1450a0dc2c96c1f8f4ce4
730d9181b3de8561c1d87d82ccb923b1859122ae
2022-08-20T01:02:16Z
c++
2022-09-09T00:08:56Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import * as https from 'https'; import * as http from 'http'; import * as path from 'path'; import * as fs from 'fs'; import * as url from 'url'; import * as ChildProcess from 'child_process'; import { EventEmitter } from 'events'; import { promisify } from 'util'; import { ifit, ifdescribe, defer, delay, itremote } from './spec-helpers'; import { AddressInfo } from 'net'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); describe('reporting api', () => { // TODO(nornagon): this started failing a lot on CI. Figure out why and fix // it. it.skip('sends a report for a deprecation', async () => { const reports = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const certPath = path.join(fixturesPath, 'certificates'); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url === '/report') { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reports.emit('report', JSON.parse(data)); }); } res.setHeader('Report-To', JSON.stringify({ group: 'default', max_age: 120, endpoints: [{ url: `https://localhost:${(server.address() as any).port}/report` }] })); res.setHeader('Content-Type', 'text/html'); // using the deprecated `webkitRequestAnimationFrame` will trigger a // "deprecation" report. res.end('<script>webkitRequestAnimationFrame(() => {})</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = emittedOnce(reports, 'report'); const url = `https://localhost:${(server.address() as any).port}/a`; await bw.loadURL(url); const [report] = await reportGenerated; expect(report).to.be.an('array'); expect(report[0].type).to.equal('deprecation'); expect(report[0].url).to.equal(url); expect(report[0].body.id).to.equal('PrefixedRequestAnimationFrame'); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await emittedOnce(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents = null as unknown as WebContents; let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = emittedOnce(w.webContents, 'did-attach-webview'); await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await emittedOnce(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await emittedOnce(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = emittedOnce(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await emittedOnce(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', 'fr')); it('should not set an invalid locale', async () => testLocale('asdfkl', currentLocale)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await new Promise(resolve => { appProcess!.on('exit', resolve); }); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await emittedOnce(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await emittedOnce(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not crash when nodeIntegration is enabled', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-worker-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); }); ifdescribe(features.isFakeLocationProviderEnabled())('navigator.geolocation', () => { it('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = emittedOnce(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); it('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), reject))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await emittedOnce(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/shared_worker.html`); const [, data] = await emittedOnce(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = emittedOnce(app, 'browser-window-created'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = emittedOnce(app, 'browser-window-created'); w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await emittedOnce(app, 'browser-window-created'); const preferences = window.webContents.getLastWebPreferences(); expect(preferences.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await emittedOnce(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await emittedOnce(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await emittedOnce(app, 'browser-window-created'); await emittedOnce(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); // TODO(nornagon): I'm not sure this ... ever was correct? it.skip('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach((done) => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); server.listen(0, '127.0.0.1', () => { serverURL = `http://127.0.0.1:${server.address().port}`; done(); }); }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds'); const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload()); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await emittedOnce(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); const [, secondDeviceIds] = await emittedOnce(ipcMain, 'deviceIds', () => w.webContents.reload()); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))'); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { (contents as any).destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = emittedOnce(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = emittedOnce(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = emittedOnce(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = emittedOnce(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = emittedOnce(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; serverCrossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('crashed', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { (contents as any).destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as any).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await emittedOnce(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = emittedOnce(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await delay(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await emittedOnce(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await emittedOnce(app, 'web-contents-created'); await emittedOnce(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = emittedOnce(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); ifdescribe(process.platform !== 'win32' && process.platform !== 'linux')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const port = (server.address() as AddressInfo).port; const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); ifdescribe(features.isTtsEnabled())('SpeechSynthesis', () => { before(function () { // TODO(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). this.skip(); }); itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow, server: http.Server; before(() => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); server.listen(8989, '127.0.0.1'); }); beforeEach(() => { w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); const html = '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>'; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await delay(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await emittedOnce(w, 'enter-full-screen'); const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); const html = '<iframe style="width: 0" frameborder=0 src="http://localhost:8989" allowfullscreen></iframe>'; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await emittedOnce(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await emittedOnce(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await emittedOnce(w, 'enter-full-screen'); const fullscreenChange = emittedOnce(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal('NotFoundError: No port selected by the user.'); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal('NotFoundError: No port selected by the user.'); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); }); describe('navigator.clipboard', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ webPreferences: { enableBlinkFeatures: 'Serial' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await new Promise(resolve => setTimeout(resolve, 10)); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('crashed', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); serverUrl = `http://localhost:${(server.address() as any).port}`; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (process.arch === 'arm64' || process.arch === 'arm') { // arm CI returns HID devices - this block may need to change if CI hardware changes. expect(haveDevices).to.be.true(); // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.empty(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
35,512
[Bug]: electron should not set a default menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An application should be in full control of the menu and thus the following code is taking startup CPU cycles when not needed: https://github.com/electron/electron/blob/bfced8cbfe6bad6d119ea9276d13aa67accc9c9a/lib/browser/init.ts#L177 At the very minimum allow an option to disable this when the application sets a menu anyway. ### Actual Behavior Electron seems to install a default menu which consumes time for no good reasons it seems: <img width="364" alt="image" src="https://user-images.githubusercontent.com/900690/187595296-0380cf75-2b92-4c69-be7c-0172124a66e7.png"> ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35512
https://github.com/electron/electron/pull/35525
b3a744db8a1aa85f27f4467ae2eb1a8c2eff0233
6ec4c7e563c4bf59abb684e593bc6c0e0ee921c6
2022-08-31T04:51:53Z
c++
2022-09-12T22:29:42Z
docs/tutorial/performance.md
--- title: Performance description: A set of guidelines for building performant Electron apps slug: performance hide_title: true toc_max_heading_level: 3 --- # Performance Developers frequently ask about strategies to optimize the performance of Electron applications. Software engineers, consumers, and framework developers do not always agree on one single definition of what "performance" means. This document outlines some of the Electron maintainers' favorite ways to reduce the amount of memory, CPU, and disk resources being used while ensuring that your app is responsive to user input and completes operations as quickly as possible. Furthermore, we want all performance strategies to maintain a high standard for your app's security. Wisdom and information about how to build performant websites with JavaScript generally applies to Electron apps, too. To a certain extent, resources discussing how to build performant Node.js applications also apply, but be careful to understand that the term "performance" means different things for a Node.js backend than it does for an application running on a client. This list is provided for your convenience – and is, much like our [security checklist][security] – not meant to exhaustive. It is probably possible to build a slow Electron app that follows all the steps outlined below. Electron is a powerful development platform that enables you, the developer, to do more or less whatever you want. All that freedom means that performance is largely your responsibility. ## Measure, Measure, Measure The list below contains a number of steps that are fairly straightforward and easy to implement. However, building the most performant version of your app will require you to go beyond a number of steps. Instead, you will have to closely examine all the code running in your app by carefully profiling and measuring. Where are the bottlenecks? When the user clicks a button, what operations take up the brunt of the time? While the app is simply idling, which objects take up the most memory? Time and time again, we have seen that the most successful strategy for building a performant Electron app is to profile the running code, find the most resource-hungry piece of it, and to optimize it. Repeating this seemingly laborious process over and over again will dramatically increase your app's performance. Experience from working with major apps like Visual Studio Code or Slack has shown that this practice is by far the most reliable strategy to improve performance. To learn more about how to profile your app's code, familiarize yourself with the Chrome Developer Tools. For advanced analysis looking at multiple processes at once, consider the [Chrome Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tool. ### Recommended Reading * [Get Started With Analyzing Runtime Performance][chrome-devtools-tutorial] * [Talk: "Visual Studio Code - The First Second"][vscode-first-second] ## Checklist: Performance recommendations Chances are that your app could be a little leaner, faster, and generally less resource-hungry if you attempt these steps. 1. [Carelessly including modules](#1-carelessly-including-modules) 2. [Loading and running code too soon](#2-loading-and-running-code-too-soon) 3. [Blocking the main process](#3-blocking-the-main-process) 4. [Blocking the renderer process](#4-blocking-the-renderer-process) 5. [Unnecessary polyfills](#5-unnecessary-polyfills) 6. [Unnecessary or blocking network requests](#6-unnecessary-or-blocking-network-requests) 7. [Bundle your code](#7-bundle-your-code) ### 1. Carelessly including modules Before adding a Node.js module to your application, examine said module. How many dependencies does that module include? What kind of resources does it need to simply be called in a `require()` statement? You might find that the module with the most downloads on the NPM package registry or the most stars on GitHub is not in fact the leanest or smallest one available. #### Why? The reasoning behind this recommendation is best illustrated with a real-world example. During the early days of Electron, reliable detection of network connectivity was a problem, resulting many apps to use a module that exposed a simple `isOnline()` method. That module detected your network connectivity by attempting to reach out to a number of well-known endpoints. For the list of those endpoints, it depended on a different module, which also contained a list of well-known ports. This dependency itself relied on a module containing information about ports, which came in the form of a JSON file with more than 100,000 lines of content. Whenever the module was loaded (usually in a `require('module')` statement), it would load all its dependencies and eventually read and parse this JSON file. Parsing many thousands lines of JSON is a very expensive operation. On a slow machine it can take up whole seconds of time. In many server contexts, startup time is virtually irrelevant. A Node.js server that requires information about all ports is likely actually "more performant" if it loads all required information into memory whenever the server boots at the benefit of serving requests faster. The module discussed in this example is not a "bad" module. Electron apps, however, should not be loading, parsing, and storing in memory information that it does not actually need. In short, a seemingly excellent module written primarily for Node.js servers running Linux might be bad news for your app's performance. In this particular example, the correct solution was to use no module at all, and to instead use connectivity checks included in later versions of Chromium. #### How? When considering a module, we recommend that you check: 1. the size of dependencies included 2. the resources required to load (`require()`) it 3. the resources required to perform the action you're interested in Generating a CPU profile and a heap memory profile for loading a module can be done with a single command on the command line. In the example below, we're looking at the popular module `request`. ```sh node --cpu-prof --heap-prof -e "require('request')" ``` Executing this command results in a `.cpuprofile` file and a `.heapprofile` file in the directory you executed it in. Both files can be analyzed using the Chrome Developer Tools, using the `Performance` and `Memory` tabs respectively. ![Performance CPU Profile](../images/performance-cpu-prof.png) ![Performance Heap Memory Profile](../images/performance-heap-prof.png) In this example, on the author's machine, we saw that loading `request` took almost half a second, whereas `node-fetch` took dramatically less memory and less than 50ms. ### 2. Loading and running code too soon If you have expensive setup operations, consider deferring those. Inspect all the work being executed right after the application starts. Instead of firing off all operations right away, consider staggering them in a sequence more closely aligned with the user's journey. In traditional Node.js development, we're used to putting all our `require()` statements at the top. If you're currently writing your Electron application using the same strategy _and_ are using sizable modules that you do not immediately need, apply the same strategy and defer loading to a more opportune time. #### Why? Loading modules is a surprisingly expensive operation, especially on Windows. When your app starts, it should not make users wait for operations that are currently not necessary. This might seem obvious, but many applications tend to do a large amount of work immediately after the app has launched - like checking for updates, downloading content used in a later flow, or performing heavy disk I/O operations. Let's consider Visual Studio Code as an example. When you open a file, it will immediately display the file to you without any code highlighting, prioritizing your ability to interact with the text. Once it has done that work, it will move on to code highlighting. #### How? Let's consider an example and assume that your application is parsing files in the fictitious `.foo` format. In order to do that, it relies on the equally fictitious `foo-parser` module. In traditional Node.js development, you might write code that eagerly loads dependencies: ```js title='parser.js' const fs = require('fs') const fooParser = require('foo-parser') class Parser { constructor () { this.files = fs.readdirSync('.') } getParsedFiles () { return fooParser.parse(this.files) } } const parser = new Parser() module.exports = { parser } ``` In the above example, we're doing a lot of work that's being executed as soon as the file is loaded. Do we need to get parsed files right away? Could we do this work a little later, when `getParsedFiles()` is actually called? ```js title='parser.js' // "fs" is likely already being loaded, so the `require()` call is cheap const fs = require('fs') class Parser { async getFiles () { // Touch the disk as soon as `getFiles` is called, not sooner. // Also, ensure that we're not blocking other operations by using // the asynchronous version. this.files = this.files || await fs.readdir('.') return this.files } async getParsedFiles () { // Our fictitious foo-parser is a big and expensive module to load, so // defer that work until we actually need to parse files. // Since `require()` comes with a module cache, the `require()` call // will only be expensive once - subsequent calls of `getParsedFiles()` // will be faster. const fooParser = require('foo-parser') const files = await this.getFiles() return fooParser.parse(files) } } // This operation is now a lot cheaper than in our previous example const parser = new Parser() module.exports = { parser } ``` In short, allocate resources "just in time" rather than allocating them all when your app starts. ### 3. Blocking the main process Electron's main process (sometimes called "browser process") is special: It is the parent process to all your app's other processes and the primary process the operating system interacts with. It handles windows, interactions, and the communication between various components inside your app. It also houses the UI thread. Under no circumstances should you block this process and the UI thread with long-running operations. Blocking the UI thread means that your entire app will freeze until the main process is ready to continue processing. #### Why? The main process and its UI thread are essentially the control tower for major operations inside your app. When the operating system tells your app about a mouse click, it'll go through the main process before it reaches your window. If your window is rendering a buttery-smooth animation, it'll need to talk to the GPU process about that – once again going through the main process. Electron and Chromium are careful to put heavy disk I/O and CPU-bound operations onto new threads to avoid blocking the UI thread. You should do the same. #### How? Electron's powerful multi-process architecture stands ready to assist you with your long-running tasks, but also includes a small number of performance traps. 1. For long running CPU-heavy tasks, make use of [worker threads][worker-threads], consider moving them to the BrowserWindow, or (as a last resort) spawn a dedicated process. 2. Avoid using the synchronous IPC and the `@electron/remote` module as much as possible. While there are legitimate use cases, it is far too easy to unknowingly block the UI thread. 3. Avoid using blocking I/O operations in the main process. In short, whenever core Node.js modules (like `fs` or `child_process`) offer a synchronous or an asynchronous version, you should prefer the asynchronous and non-blocking variant. ### 4. Blocking the renderer process Since Electron ships with a current version of Chrome, you can make use of the latest and greatest features the Web Platform offers to defer or offload heavy operations in a way that keeps your app smooth and responsive. #### Why? Your app probably has a lot of JavaScript to run in the renderer process. The trick is to execute operations as quickly as possible without taking away resources needed to keep scrolling smooth, respond to user input, or animations at 60fps. Orchestrating the flow of operations in your renderer's code is particularly useful if users complain about your app sometimes "stuttering". #### How? Generally speaking, all advice for building performant web apps for modern browsers apply to Electron's renderers, too. The two primary tools at your disposal are currently `requestIdleCallback()` for small operations and `Web Workers` for long-running operations. *`requestIdleCallback()`* allows developers to queue up a function to be executed as soon as the process is entering an idle period. It enables you to perform low-priority or background work without impacting the user experience. For more information about how to use it, [check out its documentation on MDN][request-idle-callback]. *Web Workers* are a powerful tool to run code on a separate thread. There are some caveats to consider – consult Electron's [multithreading documentation][multithreading] and the [MDN documentation for Web Workers][web-workers]. They're an ideal solution for any operation that requires a lot of CPU power for an extended period of time. ### 5. Unnecessary polyfills One of Electron's great benefits is that you know exactly which engine will parse your JavaScript, HTML, and CSS. If you're re-purposing code that was written for the web at large, make sure to not polyfill features included in Electron. #### Why? When building a web application for today's Internet, the oldest environments dictate what features you can and cannot use. Even though Electron supports well-performing CSS filters and animations, an older browser might not. Where you could use WebGL, your developers may have chosen a more resource-hungry solution to support older phones. When it comes to JavaScript, you may have included toolkit libraries like jQuery for DOM selectors or polyfills like the `regenerator-runtime` to support `async/await`. It is rare for a JavaScript-based polyfill to be faster than the equivalent native feature in Electron. Do not slow down your Electron app by shipping your own version of standard web platform features. #### How? Operate under the assumption that polyfills in current versions of Electron are unnecessary. If you have doubts, check [caniuse.com](https://caniuse.com/) and check if the [version of Chromium used in your Electron version](../api/process.md#processversionschrome-readonly) supports the feature you desire. In addition, carefully examine the libraries you use. Are they really necessary? `jQuery`, for example, was such a success that many of its features are now part of the [standard JavaScript feature set available][jquery-need]. If you're using a transpiler/compiler like TypeScript, examine its configuration and ensure that you're targeting the latest ECMAScript version supported by Electron. ### 6. Unnecessary or blocking network requests Avoid fetching rarely changing resources from the internet if they could easily be bundled with your application. #### Why? Many users of Electron start with an entirely web-based app that they're turning into a desktop application. As web developers, we are used to loading resources from a variety of content delivery networks. Now that you are shipping a proper desktop application, attempt to "cut the cord" where possible and avoid letting your users wait for resources that never change and could easily be included in your app. A typical example is Google Fonts. Many developers make use of Google's impressive collection of free fonts, which comes with a content delivery network. The pitch is straightforward: Include a few lines of CSS and Google will take care of the rest. When building an Electron app, your users are better served if you download the fonts and include them in your app's bundle. #### How? In an ideal world, your application wouldn't need the network to operate at all. To get there, you must understand what resources your app is downloading \- and how large those resources are. To do so, open up the developer tools. Navigate to the `Network` tab and check the `Disable cache` option. Then, reload your renderer. Unless your app prohibits such reloads, you can usually trigger a reload by hitting `Cmd + R` or `Ctrl + R` with the developer tools in focus. The tools will now meticulously record all network requests. In a first pass, take stock of all the resources being downloaded, focusing on the larger files first. Are any of them images, fonts, or media files that don't change and could be included with your bundle? If so, include them. As a next step, enable `Network Throttling`. Find the drop-down that currently reads `Online` and select a slower speed such as `Fast 3G`. Reload your renderer and see if there are any resources that your app is unnecessarily waiting for. In many cases, an app will wait for a network request to complete despite not actually needing the involved resource. As a tip, loading resources from the Internet that you might want to change without shipping an application update is a powerful strategy. For advanced control over how resources are being loaded, consider investing in [Service Workers][service-workers]. ### 7. Bundle your code As already pointed out in "[Loading and running code too soon](#2-loading-and-running-code-too-soon)", calling `require()` is an expensive operation. If you are able to do so, bundle your application's code into a single file. #### Why? Modern JavaScript development usually involves many files and modules. While that's perfectly fine for developing with Electron, we heavily recommend that you bundle all your code into one single file to ensure that the overhead included in calling `require()` is only paid once when your application loads. #### How? There are numerous JavaScript bundlers out there and we know better than to anger the community by recommending one tool over another. We do however recommend that you use a bundler that is able to handle Electron's unique environment that needs to handle both Node.js and browser environments. As of writing this article, the popular choices include [Webpack][webpack], [Parcel][parcel], and [rollup.js][rollup]. [security]: ./security.md [chrome-devtools-tutorial]: https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/ [worker-threads]: https://nodejs.org/api/worker_threads.html [web-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers [request-idle-callback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback [multithreading]: ./multithreading.md [caniuse]: https://caniuse.com/ [jquery-need]: http://youmightnotneedjquery.com/ [service-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API [webpack]: https://webpack.js.org/ [parcel]: https://parceljs.org/ [rollup]: https://rollupjs.org/ [vscode-first-second]: https://www.youtube.com/watch?v=r0OeHRUCCb4
closed
electron/electron
https://github.com/electron/electron
35,512
[Bug]: electron should not set a default menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An application should be in full control of the menu and thus the following code is taking startup CPU cycles when not needed: https://github.com/electron/electron/blob/bfced8cbfe6bad6d119ea9276d13aa67accc9c9a/lib/browser/init.ts#L177 At the very minimum allow an option to disable this when the application sets a menu anyway. ### Actual Behavior Electron seems to install a default menu which consumes time for no good reasons it seems: <img width="364" alt="image" src="https://user-images.githubusercontent.com/900690/187595296-0380cf75-2b92-4c69-be7c-0172124a66e7.png"> ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35512
https://github.com/electron/electron/pull/35525
b3a744db8a1aa85f27f4467ae2eb1a8c2eff0233
6ec4c7e563c4bf59abb684e593bc6c0e0ee921c6
2022-08-31T04:51:53Z
c++
2022-09-12T22:29:42Z
docs/tutorial/performance.md
--- title: Performance description: A set of guidelines for building performant Electron apps slug: performance hide_title: true toc_max_heading_level: 3 --- # Performance Developers frequently ask about strategies to optimize the performance of Electron applications. Software engineers, consumers, and framework developers do not always agree on one single definition of what "performance" means. This document outlines some of the Electron maintainers' favorite ways to reduce the amount of memory, CPU, and disk resources being used while ensuring that your app is responsive to user input and completes operations as quickly as possible. Furthermore, we want all performance strategies to maintain a high standard for your app's security. Wisdom and information about how to build performant websites with JavaScript generally applies to Electron apps, too. To a certain extent, resources discussing how to build performant Node.js applications also apply, but be careful to understand that the term "performance" means different things for a Node.js backend than it does for an application running on a client. This list is provided for your convenience – and is, much like our [security checklist][security] – not meant to exhaustive. It is probably possible to build a slow Electron app that follows all the steps outlined below. Electron is a powerful development platform that enables you, the developer, to do more or less whatever you want. All that freedom means that performance is largely your responsibility. ## Measure, Measure, Measure The list below contains a number of steps that are fairly straightforward and easy to implement. However, building the most performant version of your app will require you to go beyond a number of steps. Instead, you will have to closely examine all the code running in your app by carefully profiling and measuring. Where are the bottlenecks? When the user clicks a button, what operations take up the brunt of the time? While the app is simply idling, which objects take up the most memory? Time and time again, we have seen that the most successful strategy for building a performant Electron app is to profile the running code, find the most resource-hungry piece of it, and to optimize it. Repeating this seemingly laborious process over and over again will dramatically increase your app's performance. Experience from working with major apps like Visual Studio Code or Slack has shown that this practice is by far the most reliable strategy to improve performance. To learn more about how to profile your app's code, familiarize yourself with the Chrome Developer Tools. For advanced analysis looking at multiple processes at once, consider the [Chrome Tracing](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tool. ### Recommended Reading * [Get Started With Analyzing Runtime Performance][chrome-devtools-tutorial] * [Talk: "Visual Studio Code - The First Second"][vscode-first-second] ## Checklist: Performance recommendations Chances are that your app could be a little leaner, faster, and generally less resource-hungry if you attempt these steps. 1. [Carelessly including modules](#1-carelessly-including-modules) 2. [Loading and running code too soon](#2-loading-and-running-code-too-soon) 3. [Blocking the main process](#3-blocking-the-main-process) 4. [Blocking the renderer process](#4-blocking-the-renderer-process) 5. [Unnecessary polyfills](#5-unnecessary-polyfills) 6. [Unnecessary or blocking network requests](#6-unnecessary-or-blocking-network-requests) 7. [Bundle your code](#7-bundle-your-code) ### 1. Carelessly including modules Before adding a Node.js module to your application, examine said module. How many dependencies does that module include? What kind of resources does it need to simply be called in a `require()` statement? You might find that the module with the most downloads on the NPM package registry or the most stars on GitHub is not in fact the leanest or smallest one available. #### Why? The reasoning behind this recommendation is best illustrated with a real-world example. During the early days of Electron, reliable detection of network connectivity was a problem, resulting many apps to use a module that exposed a simple `isOnline()` method. That module detected your network connectivity by attempting to reach out to a number of well-known endpoints. For the list of those endpoints, it depended on a different module, which also contained a list of well-known ports. This dependency itself relied on a module containing information about ports, which came in the form of a JSON file with more than 100,000 lines of content. Whenever the module was loaded (usually in a `require('module')` statement), it would load all its dependencies and eventually read and parse this JSON file. Parsing many thousands lines of JSON is a very expensive operation. On a slow machine it can take up whole seconds of time. In many server contexts, startup time is virtually irrelevant. A Node.js server that requires information about all ports is likely actually "more performant" if it loads all required information into memory whenever the server boots at the benefit of serving requests faster. The module discussed in this example is not a "bad" module. Electron apps, however, should not be loading, parsing, and storing in memory information that it does not actually need. In short, a seemingly excellent module written primarily for Node.js servers running Linux might be bad news for your app's performance. In this particular example, the correct solution was to use no module at all, and to instead use connectivity checks included in later versions of Chromium. #### How? When considering a module, we recommend that you check: 1. the size of dependencies included 2. the resources required to load (`require()`) it 3. the resources required to perform the action you're interested in Generating a CPU profile and a heap memory profile for loading a module can be done with a single command on the command line. In the example below, we're looking at the popular module `request`. ```sh node --cpu-prof --heap-prof -e "require('request')" ``` Executing this command results in a `.cpuprofile` file and a `.heapprofile` file in the directory you executed it in. Both files can be analyzed using the Chrome Developer Tools, using the `Performance` and `Memory` tabs respectively. ![Performance CPU Profile](../images/performance-cpu-prof.png) ![Performance Heap Memory Profile](../images/performance-heap-prof.png) In this example, on the author's machine, we saw that loading `request` took almost half a second, whereas `node-fetch` took dramatically less memory and less than 50ms. ### 2. Loading and running code too soon If you have expensive setup operations, consider deferring those. Inspect all the work being executed right after the application starts. Instead of firing off all operations right away, consider staggering them in a sequence more closely aligned with the user's journey. In traditional Node.js development, we're used to putting all our `require()` statements at the top. If you're currently writing your Electron application using the same strategy _and_ are using sizable modules that you do not immediately need, apply the same strategy and defer loading to a more opportune time. #### Why? Loading modules is a surprisingly expensive operation, especially on Windows. When your app starts, it should not make users wait for operations that are currently not necessary. This might seem obvious, but many applications tend to do a large amount of work immediately after the app has launched - like checking for updates, downloading content used in a later flow, or performing heavy disk I/O operations. Let's consider Visual Studio Code as an example. When you open a file, it will immediately display the file to you without any code highlighting, prioritizing your ability to interact with the text. Once it has done that work, it will move on to code highlighting. #### How? Let's consider an example and assume that your application is parsing files in the fictitious `.foo` format. In order to do that, it relies on the equally fictitious `foo-parser` module. In traditional Node.js development, you might write code that eagerly loads dependencies: ```js title='parser.js' const fs = require('fs') const fooParser = require('foo-parser') class Parser { constructor () { this.files = fs.readdirSync('.') } getParsedFiles () { return fooParser.parse(this.files) } } const parser = new Parser() module.exports = { parser } ``` In the above example, we're doing a lot of work that's being executed as soon as the file is loaded. Do we need to get parsed files right away? Could we do this work a little later, when `getParsedFiles()` is actually called? ```js title='parser.js' // "fs" is likely already being loaded, so the `require()` call is cheap const fs = require('fs') class Parser { async getFiles () { // Touch the disk as soon as `getFiles` is called, not sooner. // Also, ensure that we're not blocking other operations by using // the asynchronous version. this.files = this.files || await fs.readdir('.') return this.files } async getParsedFiles () { // Our fictitious foo-parser is a big and expensive module to load, so // defer that work until we actually need to parse files. // Since `require()` comes with a module cache, the `require()` call // will only be expensive once - subsequent calls of `getParsedFiles()` // will be faster. const fooParser = require('foo-parser') const files = await this.getFiles() return fooParser.parse(files) } } // This operation is now a lot cheaper than in our previous example const parser = new Parser() module.exports = { parser } ``` In short, allocate resources "just in time" rather than allocating them all when your app starts. ### 3. Blocking the main process Electron's main process (sometimes called "browser process") is special: It is the parent process to all your app's other processes and the primary process the operating system interacts with. It handles windows, interactions, and the communication between various components inside your app. It also houses the UI thread. Under no circumstances should you block this process and the UI thread with long-running operations. Blocking the UI thread means that your entire app will freeze until the main process is ready to continue processing. #### Why? The main process and its UI thread are essentially the control tower for major operations inside your app. When the operating system tells your app about a mouse click, it'll go through the main process before it reaches your window. If your window is rendering a buttery-smooth animation, it'll need to talk to the GPU process about that – once again going through the main process. Electron and Chromium are careful to put heavy disk I/O and CPU-bound operations onto new threads to avoid blocking the UI thread. You should do the same. #### How? Electron's powerful multi-process architecture stands ready to assist you with your long-running tasks, but also includes a small number of performance traps. 1. For long running CPU-heavy tasks, make use of [worker threads][worker-threads], consider moving them to the BrowserWindow, or (as a last resort) spawn a dedicated process. 2. Avoid using the synchronous IPC and the `@electron/remote` module as much as possible. While there are legitimate use cases, it is far too easy to unknowingly block the UI thread. 3. Avoid using blocking I/O operations in the main process. In short, whenever core Node.js modules (like `fs` or `child_process`) offer a synchronous or an asynchronous version, you should prefer the asynchronous and non-blocking variant. ### 4. Blocking the renderer process Since Electron ships with a current version of Chrome, you can make use of the latest and greatest features the Web Platform offers to defer or offload heavy operations in a way that keeps your app smooth and responsive. #### Why? Your app probably has a lot of JavaScript to run in the renderer process. The trick is to execute operations as quickly as possible without taking away resources needed to keep scrolling smooth, respond to user input, or animations at 60fps. Orchestrating the flow of operations in your renderer's code is particularly useful if users complain about your app sometimes "stuttering". #### How? Generally speaking, all advice for building performant web apps for modern browsers apply to Electron's renderers, too. The two primary tools at your disposal are currently `requestIdleCallback()` for small operations and `Web Workers` for long-running operations. *`requestIdleCallback()`* allows developers to queue up a function to be executed as soon as the process is entering an idle period. It enables you to perform low-priority or background work without impacting the user experience. For more information about how to use it, [check out its documentation on MDN][request-idle-callback]. *Web Workers* are a powerful tool to run code on a separate thread. There are some caveats to consider – consult Electron's [multithreading documentation][multithreading] and the [MDN documentation for Web Workers][web-workers]. They're an ideal solution for any operation that requires a lot of CPU power for an extended period of time. ### 5. Unnecessary polyfills One of Electron's great benefits is that you know exactly which engine will parse your JavaScript, HTML, and CSS. If you're re-purposing code that was written for the web at large, make sure to not polyfill features included in Electron. #### Why? When building a web application for today's Internet, the oldest environments dictate what features you can and cannot use. Even though Electron supports well-performing CSS filters and animations, an older browser might not. Where you could use WebGL, your developers may have chosen a more resource-hungry solution to support older phones. When it comes to JavaScript, you may have included toolkit libraries like jQuery for DOM selectors or polyfills like the `regenerator-runtime` to support `async/await`. It is rare for a JavaScript-based polyfill to be faster than the equivalent native feature in Electron. Do not slow down your Electron app by shipping your own version of standard web platform features. #### How? Operate under the assumption that polyfills in current versions of Electron are unnecessary. If you have doubts, check [caniuse.com](https://caniuse.com/) and check if the [version of Chromium used in your Electron version](../api/process.md#processversionschrome-readonly) supports the feature you desire. In addition, carefully examine the libraries you use. Are they really necessary? `jQuery`, for example, was such a success that many of its features are now part of the [standard JavaScript feature set available][jquery-need]. If you're using a transpiler/compiler like TypeScript, examine its configuration and ensure that you're targeting the latest ECMAScript version supported by Electron. ### 6. Unnecessary or blocking network requests Avoid fetching rarely changing resources from the internet if they could easily be bundled with your application. #### Why? Many users of Electron start with an entirely web-based app that they're turning into a desktop application. As web developers, we are used to loading resources from a variety of content delivery networks. Now that you are shipping a proper desktop application, attempt to "cut the cord" where possible and avoid letting your users wait for resources that never change and could easily be included in your app. A typical example is Google Fonts. Many developers make use of Google's impressive collection of free fonts, which comes with a content delivery network. The pitch is straightforward: Include a few lines of CSS and Google will take care of the rest. When building an Electron app, your users are better served if you download the fonts and include them in your app's bundle. #### How? In an ideal world, your application wouldn't need the network to operate at all. To get there, you must understand what resources your app is downloading \- and how large those resources are. To do so, open up the developer tools. Navigate to the `Network` tab and check the `Disable cache` option. Then, reload your renderer. Unless your app prohibits such reloads, you can usually trigger a reload by hitting `Cmd + R` or `Ctrl + R` with the developer tools in focus. The tools will now meticulously record all network requests. In a first pass, take stock of all the resources being downloaded, focusing on the larger files first. Are any of them images, fonts, or media files that don't change and could be included with your bundle? If so, include them. As a next step, enable `Network Throttling`. Find the drop-down that currently reads `Online` and select a slower speed such as `Fast 3G`. Reload your renderer and see if there are any resources that your app is unnecessarily waiting for. In many cases, an app will wait for a network request to complete despite not actually needing the involved resource. As a tip, loading resources from the Internet that you might want to change without shipping an application update is a powerful strategy. For advanced control over how resources are being loaded, consider investing in [Service Workers][service-workers]. ### 7. Bundle your code As already pointed out in "[Loading and running code too soon](#2-loading-and-running-code-too-soon)", calling `require()` is an expensive operation. If you are able to do so, bundle your application's code into a single file. #### Why? Modern JavaScript development usually involves many files and modules. While that's perfectly fine for developing with Electron, we heavily recommend that you bundle all your code into one single file to ensure that the overhead included in calling `require()` is only paid once when your application loads. #### How? There are numerous JavaScript bundlers out there and we know better than to anger the community by recommending one tool over another. We do however recommend that you use a bundler that is able to handle Electron's unique environment that needs to handle both Node.js and browser environments. As of writing this article, the popular choices include [Webpack][webpack], [Parcel][parcel], and [rollup.js][rollup]. [security]: ./security.md [chrome-devtools-tutorial]: https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/ [worker-threads]: https://nodejs.org/api/worker_threads.html [web-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers [request-idle-callback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback [multithreading]: ./multithreading.md [caniuse]: https://caniuse.com/ [jquery-need]: http://youmightnotneedjquery.com/ [service-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API [webpack]: https://webpack.js.org/ [parcel]: https://parceljs.org/ [rollup]: https://rollupjs.org/ [vscode-first-second]: https://www.youtube.com/watch?v=r0OeHRUCCb4
closed
electron/electron
https://github.com/electron/electron
35,594
[Bug]: File extension appended multiple times to file name when saving
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.1 All latest 18.x.y, 19.x.y and 20.x.y versions are affected. ### What operating system are you using? Windows ### Operating System Version Windows 10 Version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.7 ### Expected Behavior When saving/downloading a file, file name should be saved with the given file extension. ### Actual Behavior File extension is appended three times to file name with double dots, like: <file_name>.<file_extension>..<file_extension>..<file_extension> Issue happens for file extensions which are not in registry. For file types which are in registry, file name is fine. ### Testcase Gist URL https://gist.github.com/dfa6a6e75b43e475f285df9e0f743650 ### Additional Information Most likely related to the change https://github.com/electron/electron/pull/34723
https://github.com/electron/electron/issues/35594
https://github.com/electron/electron/pull/35618
9f97c3e50a11b364f02f57209854bb4000ac1136
12a7d7eea52409ce02af6d5f51f8208f483f24d2
2022-09-07T14:47:00Z
c++
2022-09-13T18:47:04Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" #if BUILDFLAG(IS_WIN) #include <vector> #include "base/i18n/case_conversion.h" #include "base/win/registry.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/strings/grit/ui_strings.h" #endif // BUILDFLAG(IS_WIN) namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } #if BUILDFLAG(IS_WIN) // Get the file type description from the registry. This will be "Text Document" // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't // have an entry for the file type, we return false, true if the description was // found. 'file_ext' must be in form ".txt". // Modified from ui/shell_dialogs/select_file_dialog_win.cc bool GetRegistryDescriptionFromExtension(const std::string& file_ext, std::string* reg_description) { DCHECK(reg_description); base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, base::UTF8ToWide(file_ext).c_str(), KEY_READ); std::wstring reg_app; if (reg_ext.ReadValue(nullptr, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) { base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); std::wstring description; if (reg_link.ReadValue(nullptr, &description) == ERROR_SUCCESS) { *reg_description = base::WideToUTF8(description); return true; } } return false; } // Set up a filter for a Save/Open dialog, |ext_desc| as the text descriptions // of the |file_ext| types (optional), and (optionally) the default 'All Files' // view. The purpose of the filter is to show only files of a particular type in // a Windows Save/Open dialog box. The resulting filter is returned. The filter // created here are: // 1. only files that have 'file_ext' as their extension // 2. all files (only added if 'include_all_files' is true) // If a description is not provided for a file extension, it will be retrieved // from the registry. If the file extension does not exist in the registry, a // default description will be created (e.g. "qqq" yields "QQQ File"). // Copied from ui/shell_dialogs/select_file_dialog_win.cc file_dialog::Filters FormatFilterForExtensions( const std::vector<std::string>& file_ext, const std::vector<std::string>& ext_desc, bool include_all_files, bool keep_extension_visible) { const std::string all_ext = "*"; const std::string all_desc = l10n_util::GetStringUTF8(IDS_APP_SAVEAS_ALL_FILES); DCHECK(file_ext.size() >= ext_desc.size()); if (file_ext.empty()) include_all_files = true; file_dialog::Filters result; result.reserve(file_ext.size() + 1); for (size_t i = 0; i < file_ext.size(); ++i) { std::string ext = file_ext[i]; std::string desc; if (i < ext_desc.size()) desc = ext_desc[i]; if (ext.empty()) { // Force something reasonable to appear in the dialog box if there is no // extension provided. include_all_files = true; continue; } if (desc.empty()) { DCHECK(ext.find('.') != std::string::npos); std::string first_extension = ext.substr(ext.find('.')); size_t first_separator_index = first_extension.find(';'); if (first_separator_index != std::string::npos) first_extension = first_extension.substr(0, first_separator_index); // Find the extension name without the preceeding '.' character. std::string ext_name = first_extension; size_t ext_index = ext_name.find_first_not_of('.'); if (ext_index != std::string::npos) ext_name = ext_name.substr(ext_index); if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { // The extension doesn't exist in the registry. Create a description // based on the unknown extension type (i.e. if the extension is .qqq, // then we create a description "QQQ File"). desc = l10n_util::GetStringFUTF8( IDS_APP_SAVEAS_EXTENSION_FORMAT, base::i18n::ToUpper(base::UTF8ToUTF16(ext_name))); include_all_files = true; } if (desc.empty()) desc = "*." + ext_name; } else if (keep_extension_visible) { // Having '*' in the description could cause the windows file dialog to // not include the file extension in the file dialog. So strip out any '*' // characters if `keep_extension_visible` is set. base::ReplaceChars(desc, "*", base::StringPiece(), &desc); } result.push_back({desc, {ext}}); } if (include_all_files) result.push_back({all_desc, {all_ext}}); return result; } #endif // BUILDFLAG(IS_WIN) } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; #if BUILDFLAG(IS_WIN) if (settings.filters.empty()) { const std::wstring extension = settings.default_path.FinalExtension(); if (!extension.empty()) { settings.filters = FormatFilterForExtensions( {base::WideToUTF8(extension)}, {""}, true, true); } } #endif // BUILDFLAG(IS_WIN) v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,429
[Bug]: When downloading a file using the video tag, an extra character dot appears when saving the file!
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.6 ### Expected Behavior ### When the video tag was used to download files, the save type was normal. ### Actual Behavior ## When downloading a file using the video tag, an extra character dot appears when saving the file! It has two character dot in the file type. ![image](https://user-images.githubusercontent.com/41336612/186472381-b42fe64d-6631-4def-88bd-48d10591cbd4.png) ![image](https://user-images.githubusercontent.com/41336612/186471193-e2558aaf-4e7c-4a51-8fca-e3db0f9731df.png) ### Testcase Gist URL https://gist.github.com/liulinboyi/2e687fbf07f0d9c836933817046ea043 ### Additional Information ### I have a feeling that this bug exists from version 20.
https://github.com/electron/electron/issues/35429
https://github.com/electron/electron/pull/35618
9f97c3e50a11b364f02f57209854bb4000ac1136
12a7d7eea52409ce02af6d5f51f8208f483f24d2
2022-08-24T16:35:28Z
c++
2022-09-13T18:47:04Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" #if BUILDFLAG(IS_WIN) #include <vector> #include "base/i18n/case_conversion.h" #include "base/win/registry.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/strings/grit/ui_strings.h" #endif // BUILDFLAG(IS_WIN) namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } #if BUILDFLAG(IS_WIN) // Get the file type description from the registry. This will be "Text Document" // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't // have an entry for the file type, we return false, true if the description was // found. 'file_ext' must be in form ".txt". // Modified from ui/shell_dialogs/select_file_dialog_win.cc bool GetRegistryDescriptionFromExtension(const std::string& file_ext, std::string* reg_description) { DCHECK(reg_description); base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, base::UTF8ToWide(file_ext).c_str(), KEY_READ); std::wstring reg_app; if (reg_ext.ReadValue(nullptr, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) { base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); std::wstring description; if (reg_link.ReadValue(nullptr, &description) == ERROR_SUCCESS) { *reg_description = base::WideToUTF8(description); return true; } } return false; } // Set up a filter for a Save/Open dialog, |ext_desc| as the text descriptions // of the |file_ext| types (optional), and (optionally) the default 'All Files' // view. The purpose of the filter is to show only files of a particular type in // a Windows Save/Open dialog box. The resulting filter is returned. The filter // created here are: // 1. only files that have 'file_ext' as their extension // 2. all files (only added if 'include_all_files' is true) // If a description is not provided for a file extension, it will be retrieved // from the registry. If the file extension does not exist in the registry, a // default description will be created (e.g. "qqq" yields "QQQ File"). // Copied from ui/shell_dialogs/select_file_dialog_win.cc file_dialog::Filters FormatFilterForExtensions( const std::vector<std::string>& file_ext, const std::vector<std::string>& ext_desc, bool include_all_files, bool keep_extension_visible) { const std::string all_ext = "*"; const std::string all_desc = l10n_util::GetStringUTF8(IDS_APP_SAVEAS_ALL_FILES); DCHECK(file_ext.size() >= ext_desc.size()); if (file_ext.empty()) include_all_files = true; file_dialog::Filters result; result.reserve(file_ext.size() + 1); for (size_t i = 0; i < file_ext.size(); ++i) { std::string ext = file_ext[i]; std::string desc; if (i < ext_desc.size()) desc = ext_desc[i]; if (ext.empty()) { // Force something reasonable to appear in the dialog box if there is no // extension provided. include_all_files = true; continue; } if (desc.empty()) { DCHECK(ext.find('.') != std::string::npos); std::string first_extension = ext.substr(ext.find('.')); size_t first_separator_index = first_extension.find(';'); if (first_separator_index != std::string::npos) first_extension = first_extension.substr(0, first_separator_index); // Find the extension name without the preceeding '.' character. std::string ext_name = first_extension; size_t ext_index = ext_name.find_first_not_of('.'); if (ext_index != std::string::npos) ext_name = ext_name.substr(ext_index); if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { // The extension doesn't exist in the registry. Create a description // based on the unknown extension type (i.e. if the extension is .qqq, // then we create a description "QQQ File"). desc = l10n_util::GetStringFUTF8( IDS_APP_SAVEAS_EXTENSION_FORMAT, base::i18n::ToUpper(base::UTF8ToUTF16(ext_name))); include_all_files = true; } if (desc.empty()) desc = "*." + ext_name; } else if (keep_extension_visible) { // Having '*' in the description could cause the windows file dialog to // not include the file extension in the file dialog. So strip out any '*' // characters if `keep_extension_visible` is set. base::ReplaceChars(desc, "*", base::StringPiece(), &desc); } result.push_back({desc, {ext}}); } if (include_all_files) result.push_back({all_desc, {all_ext}}); return result; } #endif // BUILDFLAG(IS_WIN) } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; #if BUILDFLAG(IS_WIN) if (settings.filters.empty()) { const std::wstring extension = settings.default_path.FinalExtension(); if (!extension.empty()) { settings.filters = FormatFilterForExtensions( {base::WideToUTF8(extension)}, {""}, true, true); } } #endif // BUILDFLAG(IS_WIN) v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,594
[Bug]: File extension appended multiple times to file name when saving
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.1.1 All latest 18.x.y, 19.x.y and 20.x.y versions are affected. ### What operating system are you using? Windows ### Operating System Version Windows 10 Version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.7 ### Expected Behavior When saving/downloading a file, file name should be saved with the given file extension. ### Actual Behavior File extension is appended three times to file name with double dots, like: <file_name>.<file_extension>..<file_extension>..<file_extension> Issue happens for file extensions which are not in registry. For file types which are in registry, file name is fine. ### Testcase Gist URL https://gist.github.com/dfa6a6e75b43e475f285df9e0f743650 ### Additional Information Most likely related to the change https://github.com/electron/electron/pull/34723
https://github.com/electron/electron/issues/35594
https://github.com/electron/electron/pull/35618
9f97c3e50a11b364f02f57209854bb4000ac1136
12a7d7eea52409ce02af6d5f51f8208f483f24d2
2022-09-07T14:47:00Z
c++
2022-09-13T18:47:04Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" #if BUILDFLAG(IS_WIN) #include <vector> #include "base/i18n/case_conversion.h" #include "base/win/registry.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/strings/grit/ui_strings.h" #endif // BUILDFLAG(IS_WIN) namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } #if BUILDFLAG(IS_WIN) // Get the file type description from the registry. This will be "Text Document" // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't // have an entry for the file type, we return false, true if the description was // found. 'file_ext' must be in form ".txt". // Modified from ui/shell_dialogs/select_file_dialog_win.cc bool GetRegistryDescriptionFromExtension(const std::string& file_ext, std::string* reg_description) { DCHECK(reg_description); base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, base::UTF8ToWide(file_ext).c_str(), KEY_READ); std::wstring reg_app; if (reg_ext.ReadValue(nullptr, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) { base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); std::wstring description; if (reg_link.ReadValue(nullptr, &description) == ERROR_SUCCESS) { *reg_description = base::WideToUTF8(description); return true; } } return false; } // Set up a filter for a Save/Open dialog, |ext_desc| as the text descriptions // of the |file_ext| types (optional), and (optionally) the default 'All Files' // view. The purpose of the filter is to show only files of a particular type in // a Windows Save/Open dialog box. The resulting filter is returned. The filter // created here are: // 1. only files that have 'file_ext' as their extension // 2. all files (only added if 'include_all_files' is true) // If a description is not provided for a file extension, it will be retrieved // from the registry. If the file extension does not exist in the registry, a // default description will be created (e.g. "qqq" yields "QQQ File"). // Copied from ui/shell_dialogs/select_file_dialog_win.cc file_dialog::Filters FormatFilterForExtensions( const std::vector<std::string>& file_ext, const std::vector<std::string>& ext_desc, bool include_all_files, bool keep_extension_visible) { const std::string all_ext = "*"; const std::string all_desc = l10n_util::GetStringUTF8(IDS_APP_SAVEAS_ALL_FILES); DCHECK(file_ext.size() >= ext_desc.size()); if (file_ext.empty()) include_all_files = true; file_dialog::Filters result; result.reserve(file_ext.size() + 1); for (size_t i = 0; i < file_ext.size(); ++i) { std::string ext = file_ext[i]; std::string desc; if (i < ext_desc.size()) desc = ext_desc[i]; if (ext.empty()) { // Force something reasonable to appear in the dialog box if there is no // extension provided. include_all_files = true; continue; } if (desc.empty()) { DCHECK(ext.find('.') != std::string::npos); std::string first_extension = ext.substr(ext.find('.')); size_t first_separator_index = first_extension.find(';'); if (first_separator_index != std::string::npos) first_extension = first_extension.substr(0, first_separator_index); // Find the extension name without the preceeding '.' character. std::string ext_name = first_extension; size_t ext_index = ext_name.find_first_not_of('.'); if (ext_index != std::string::npos) ext_name = ext_name.substr(ext_index); if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { // The extension doesn't exist in the registry. Create a description // based on the unknown extension type (i.e. if the extension is .qqq, // then we create a description "QQQ File"). desc = l10n_util::GetStringFUTF8( IDS_APP_SAVEAS_EXTENSION_FORMAT, base::i18n::ToUpper(base::UTF8ToUTF16(ext_name))); include_all_files = true; } if (desc.empty()) desc = "*." + ext_name; } else if (keep_extension_visible) { // Having '*' in the description could cause the windows file dialog to // not include the file extension in the file dialog. So strip out any '*' // characters if `keep_extension_visible` is set. base::ReplaceChars(desc, "*", base::StringPiece(), &desc); } result.push_back({desc, {ext}}); } if (include_all_files) result.push_back({all_desc, {all_ext}}); return result; } #endif // BUILDFLAG(IS_WIN) } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; #if BUILDFLAG(IS_WIN) if (settings.filters.empty()) { const std::wstring extension = settings.default_path.FinalExtension(); if (!extension.empty()) { settings.filters = FormatFilterForExtensions( {base::WideToUTF8(extension)}, {""}, true, true); } } #endif // BUILDFLAG(IS_WIN) v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,429
[Bug]: When downloading a file using the video tag, an extra character dot appears when saving the file!
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 20.0.3 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.6 ### Expected Behavior ### When the video tag was used to download files, the save type was normal. ### Actual Behavior ## When downloading a file using the video tag, an extra character dot appears when saving the file! It has two character dot in the file type. ![image](https://user-images.githubusercontent.com/41336612/186472381-b42fe64d-6631-4def-88bd-48d10591cbd4.png) ![image](https://user-images.githubusercontent.com/41336612/186471193-e2558aaf-4e7c-4a51-8fca-e3db0f9731df.png) ### Testcase Gist URL https://gist.github.com/liulinboyi/2e687fbf07f0d9c836933817046ea043 ### Additional Information ### I have a feeling that this bug exists from version 20.
https://github.com/electron/electron/issues/35429
https://github.com/electron/electron/pull/35618
9f97c3e50a11b364f02f57209854bb4000ac1136
12a7d7eea52409ce02af6d5f51f8208f483f24d2
2022-08-24T16:35:28Z
c++
2022-09-13T18:47:04Z
shell/browser/electron_download_manager_delegate.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_download_manager_delegate.h" #include <string> #include <tuple> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_window.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/options_switches.h" #if BUILDFLAG(IS_WIN) #include <vector> #include "base/i18n/case_conversion.h" #include "base/win/registry.h" #include "ui/base/l10n/l10n_util.h" #include "ui/shell_dialogs/execute_select_file_win.h" #include "ui/strings/grit/ui_strings.h" #endif // BUILDFLAG(IS_WIN) namespace electron { namespace { // Generate default file path to save the download. base::FilePath CreateDownloadPath(const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& last_saved_directory, const base::FilePath& default_download_path) { auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); base::FilePath download_path; // If the last saved directory is a non-empty existent path, use it as the // default. if (last_saved_directory.empty() || !base::PathExists(last_saved_directory)) { download_path = default_download_path; if (!base::PathExists(download_path)) base::CreateDirectory(download_path); } else { // Otherwise use the global default. download_path = last_saved_directory; } return download_path.Append(generated_name); } #if BUILDFLAG(IS_WIN) // Get the file type description from the registry. This will be "Text Document" // for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't // have an entry for the file type, we return false, true if the description was // found. 'file_ext' must be in form ".txt". // Modified from ui/shell_dialogs/select_file_dialog_win.cc bool GetRegistryDescriptionFromExtension(const std::string& file_ext, std::string* reg_description) { DCHECK(reg_description); base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, base::UTF8ToWide(file_ext).c_str(), KEY_READ); std::wstring reg_app; if (reg_ext.ReadValue(nullptr, &reg_app) == ERROR_SUCCESS && !reg_app.empty()) { base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); std::wstring description; if (reg_link.ReadValue(nullptr, &description) == ERROR_SUCCESS) { *reg_description = base::WideToUTF8(description); return true; } } return false; } // Set up a filter for a Save/Open dialog, |ext_desc| as the text descriptions // of the |file_ext| types (optional), and (optionally) the default 'All Files' // view. The purpose of the filter is to show only files of a particular type in // a Windows Save/Open dialog box. The resulting filter is returned. The filter // created here are: // 1. only files that have 'file_ext' as their extension // 2. all files (only added if 'include_all_files' is true) // If a description is not provided for a file extension, it will be retrieved // from the registry. If the file extension does not exist in the registry, a // default description will be created (e.g. "qqq" yields "QQQ File"). // Copied from ui/shell_dialogs/select_file_dialog_win.cc file_dialog::Filters FormatFilterForExtensions( const std::vector<std::string>& file_ext, const std::vector<std::string>& ext_desc, bool include_all_files, bool keep_extension_visible) { const std::string all_ext = "*"; const std::string all_desc = l10n_util::GetStringUTF8(IDS_APP_SAVEAS_ALL_FILES); DCHECK(file_ext.size() >= ext_desc.size()); if (file_ext.empty()) include_all_files = true; file_dialog::Filters result; result.reserve(file_ext.size() + 1); for (size_t i = 0; i < file_ext.size(); ++i) { std::string ext = file_ext[i]; std::string desc; if (i < ext_desc.size()) desc = ext_desc[i]; if (ext.empty()) { // Force something reasonable to appear in the dialog box if there is no // extension provided. include_all_files = true; continue; } if (desc.empty()) { DCHECK(ext.find('.') != std::string::npos); std::string first_extension = ext.substr(ext.find('.')); size_t first_separator_index = first_extension.find(';'); if (first_separator_index != std::string::npos) first_extension = first_extension.substr(0, first_separator_index); // Find the extension name without the preceeding '.' character. std::string ext_name = first_extension; size_t ext_index = ext_name.find_first_not_of('.'); if (ext_index != std::string::npos) ext_name = ext_name.substr(ext_index); if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { // The extension doesn't exist in the registry. Create a description // based on the unknown extension type (i.e. if the extension is .qqq, // then we create a description "QQQ File"). desc = l10n_util::GetStringFUTF8( IDS_APP_SAVEAS_EXTENSION_FORMAT, base::i18n::ToUpper(base::UTF8ToUTF16(ext_name))); include_all_files = true; } if (desc.empty()) desc = "*." + ext_name; } else if (keep_extension_visible) { // Having '*' in the description could cause the windows file dialog to // not include the file extension in the file dialog. So strip out any '*' // characters if `keep_extension_visible` is set. base::ReplaceChars(desc, "*", base::StringPiece(), &desc); } result.push_back({desc, {ext}}); } if (include_all_files) result.push_back({all_desc, {all_ext}}); return result; } #endif // BUILDFLAG(IS_WIN) } // namespace ElectronDownloadManagerDelegate::ElectronDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager) {} ElectronDownloadManagerDelegate::~ElectronDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void ElectronDownloadManagerDelegate::GetItemSavePath( download::DownloadItem* item, base::FilePath* path) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *path = download->GetSavePath(); } void ElectronDownloadManagerDelegate::GetItemSaveDialogOptions( download::DownloadItem* item, file_dialog::DialogSettings* options) { api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) *options = download->GetSaveDialogOptions(); } void ElectronDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, content::DownloadTargetCallback callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); base::ThreadRestrictions::ScopedAllowIO allow_io; auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->GetNativeWindow(); // Show save dialog if save path was not set already on item base::FilePath path; GetItemSavePath(item, &path); if (path.empty()) { file_dialog::DialogSettings settings; GetItemSaveDialogOptions(item, &settings); if (!settings.parent_window) settings.parent_window = window; if (settings.title.empty()) settings.title = item->GetURL().spec(); if (settings.default_path.empty()) settings.default_path = default_path; auto* web_preferences = WebContentsPreferences::From(web_contents); const bool offscreen = !web_preferences || web_preferences->IsOffscreen(); settings.force_detached = offscreen; #if BUILDFLAG(IS_WIN) if (settings.filters.empty()) { const std::wstring extension = settings.default_path.FinalExtension(); if (!extension.empty()) { settings.filters = FormatFilterForExtensions( {base::WideToUTF8(extension)}, {""}, true, true); } } #endif // BUILDFLAG(IS_WIN) v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::Promise<gin_helper::Dictionary> dialog_promise(isolate); auto dialog_callback = base::BindOnce( &ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone, base::Unretained(this), download_id, std::move(callback)); std::ignore = dialog_promise.Then(std::move(dialog_callback)); file_dialog::ShowSaveDialog(settings, std::move(dialog_promise)); } else { std::move(callback).Run( path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); } } void ElectronDownloadManagerDelegate::OnDownloadSaveDialogDone( uint32_t download_id, content::DownloadTargetCallback download_callback, gin_helper::Dictionary result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; bool canceled = true; result.Get("canceled", &canceled); base::FilePath path; if (!canceled) { if (result.Get("filePath", &path)) { // Remember the last selected download directory. last_saved_directory_ = path.DirName(); api::DownloadItem* download = api::DownloadItem::FromDownloadItem(item); if (download) download->SetSavePath(path); } } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. If user cancels the file save dialog, run // the callback with empty FilePath. const auto interrupt_reason = path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : download::DOWNLOAD_INTERRUPT_REASON_NONE; std::move(download_callback) .Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, item->GetMixedContentStatus(), path, base::FilePath(), std::string() /*mime_type*/, interrupt_reason); } void ElectronDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool ElectronDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* download, content::DownloadTargetCallback* callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { std::move(*callback).Run( download->GetForcedFilePath(), download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, download->GetForcedFilePath(), base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { std::move(*callback).Run( save_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DownloadItem::MixedContentStatus::UNKNOWN, save_path, base::FilePath(), std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } auto* browser_context = static_cast<ElectronBrowserContext*>( download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), last_saved_directory_, default_download_path), base::BindOnce(&ElectronDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), std::move(*callback))); return true; } bool ElectronDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* download, content::DownloadOpenDelayedCallback callback) { return true; } void ElectronDownloadManagerDelegate::GetNextId( content::DownloadIdCallback callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; std::move(callback).Run(next_id++); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can contain: `appcache`, `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can contain: `temporary`, `persistent`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99", "https://x.*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. window.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. window.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `media` - Request access to media devices such as camera, microphone and speakers. * `display-capture` - Request access to capture the screen. * `mediaKeySystem` - Request access to DRM protected content. * `geolocation` - Request access to user's current location. * `notifications` - Request notification creation and the ability to display them in the user's system tray. * `midi` - Request MIDI access in the `webmidi` API. * `midiSysex` - Request the use of system exclusive messages in the `webmidi` API. * `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. These requests always appear to originate from the main frame. * `fullscreen` - Request for the app to enter fullscreen mode. * `openExternal` - Request to open links in external applications. * `unknown` - An unrecognized permission request * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`. * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDisplayMediaRequestHandler(handler)` * `handler` Function | null * `request` Object * `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media. * `securityOrigin` String - Origin of the page making the request. * `videoRequested` Boolean - true if the web content requested a video stream. * `audioRequested` Boolean - true if the web content requested an audio stream. * `userGesture` Boolean - Whether a user gesture was active when this request was triggered. * `callback` Function * `streams` Object * `video` Object | [WebFrameMain](web-frame-main.md) (optional) * `id` String - The id of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `name` String - The name of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If a string is specified, can be `loopback` or `loopbackWithMute`. Specifying a loopback device will capture system audio, and is currently only supported on Windows. If a WebFrameMain is specified, will capture audio from that frame. This handler will be called when web content requests access to display media via the `navigator.mediaDevices.getDisplayMedia` API. Use the [desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant access to. ```javascript const { session, desktopCapturer } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0] }) }) }) ``` Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream will capture the video or audio stream from that frame. ```javascript const { session } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { // Allow the tab to capture itself. callback({ video: request.frame }) }) ``` Passing `null` instead of a function resets the handler to its default state. #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permision in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url)` * `url` string Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('path') app.on('ready', async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension` | `null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` Returns `string | null` - The absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(`${__dirname}/${url}`) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
shell/browser/api/electron_api_session.cc
// Copyright (c) 2015 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_session.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/download/public/common/download_url_parameters.h" #include "components/prefs/pref_service.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "components/proxy_config/proxy_prefs.h" #include "content/browser/code_cache/generated_code_cache_context.h" // nogncheck #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/network_service_instance.h" #include "content/public/browser/storage_partition.h" #include "gin/arguments.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "net/base/completion_repeating_callback.h" #include "net/base/load_flags.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_preferences.h" #include "net/http/http_cache.h" #include "net/http/http_util.h" #include "services/network/network_service.h" #include "services/network/public/cpp/features.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_cookies.h" #include "shell/browser/api/electron_api_data_pipe_holder.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/api/electron_api_net_log.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_service_worker_context.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/browser.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_device_id_salt.h" #include "shell/browser/net/cert_verifier_client.h" #include "shell/browser/session_preferences.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/gurl_converter.h" #include "shell/common/gin_converters/media_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/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #include "ui/base/l10n/l10n_util.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/extension_registry.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/common/gin_converters/extension_converter.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #include "chrome/browser/spellchecker/spellcheck_service.h" // nogncheck #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) #include "components/spellcheck/browser/spellcheck_platform.h" #include "components/spellcheck/common/spellcheck_features.h" #endif #endif using content::BrowserThread; using content::StoragePartition; namespace predictors { // NOTE(nornagon): this is copied from // //chrome/browser/predictors/resource_prefetch_predictor.cc we don't need // anything in that file other than this constructor. Without it we get a link // error. Probably upstream the constructor should be moved to // preconnect_manager.cc. PreconnectRequest::PreconnectRequest( const url::Origin& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); } } // namespace predictors namespace { struct ClearStorageDataOptions { blink::StorageKey storage_key; uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL; uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL; }; uint32_t GetStorageMask(const std::vector<std::string>& storage_types) { uint32_t storage_mask = 0; for (const auto& it : storage_types) { auto type = base::ToLowerASCII(it); if (type == "cookies") storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; else if (type == "filesystem") storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; else if (type == "indexdb") storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; else if (type == "localstorage") storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; else if (type == "shadercache") storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; else if (type == "websql") storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; else if (type == "serviceworkers") storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; else if (type == "cachestorage") storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; } return storage_mask; } uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) { uint32_t quota_mask = 0; for (const auto& it : quota_types) { auto type = base::ToLowerASCII(it); if (type == "temporary") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY; else if (type == "persistent") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT; else if (type == "syncable") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE; } return quota_mask; } } // namespace namespace gin { template <> struct Converter<ClearStorageDataOptions> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, ClearStorageDataOptions* out) { gin_helper::Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; if (GURL storage_origin; options.Get("origin", &storage_origin)) out->storage_key = blink::StorageKey(url::Origin::Create(storage_origin)); std::vector<std::string> types; if (options.Get("storages", &types)) out->storage_types = GetStorageMask(types); if (options.Get("quotas", &types)) out->quota_types = GetQuotaMask(types); return true; } }; bool SSLProtocolVersionFromString(const std::string& version_str, network::mojom::SSLVersion* version) { if (version_str == switches::kSSLVersionTLSv12) { *version = network::mojom::SSLVersion::kTLS12; return true; } if (version_str == switches::kSSLVersionTLSv13) { *version = network::mojom::SSLVersion::kTLS13; return true; } return false; } template <> struct Converter<uint16_t> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, uint16_t* out) { auto maybe = val->IntegerValue(isolate->GetCurrentContext()); if (maybe.IsNothing()) return false; *out = maybe.FromJust(); return true; } }; template <> struct Converter<network::mojom::SSLConfigPtr> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, network::mojom::SSLConfigPtr* out) { gin_helper::Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; *out = network::mojom::SSLConfig::New(); std::string version_min_str; if (options.Get("minVersion", &version_min_str)) { if (!SSLProtocolVersionFromString(version_min_str, &(*out)->version_min)) return false; } std::string version_max_str; if (options.Get("maxVersion", &version_max_str)) { if (!SSLProtocolVersionFromString(version_max_str, &(*out)->version_max) || (*out)->version_max < network::mojom::SSLVersion::kTLS12) return false; } if (options.Has("disabledCipherSuites") && !options.Get("disabledCipherSuites", &(*out)->disabled_cipher_suites)) { return false; } std::sort((*out)->disabled_cipher_suites.begin(), (*out)->disabled_cipher_suites.end()); // TODO(nornagon): also support other SSLConfig properties? return true; } }; } // namespace gin namespace electron::api { namespace { const char kPersistPrefix[] = "persist:"; void DownloadIdCallback(content::DownloadManager* download_manager, const base::FilePath& path, const std::vector<GURL>& url_chain, const std::string& mime_type, int64_t offset, int64_t length, const std::string& last_modified, const std::string& etag, const base::Time& start_time, uint32_t id) { download_manager->CreateDownloadItem( base::GenerateGUID(), id, path, path, url_chain, GURL(), content::StoragePartitionConfig::CreateDefault( download_manager->GetBrowserContext()), GURL(), GURL(), absl::nullopt, mime_type, mime_type, start_time, base::Time(), etag, last_modified, offset, length, std::string(), download::DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(), false, std::vector<download::DownloadItem::ReceivedSlice>(), download::DownloadItemRerouteInfo()); } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) class DictionaryObserver final : public SpellcheckCustomDictionary::Observer { private: std::unique_ptr<gin_helper::Promise<std::set<std::string>>> promise_; base::WeakPtr<SpellcheckService> spellcheck_; public: DictionaryObserver(gin_helper::Promise<std::set<std::string>> promise, base::WeakPtr<SpellcheckService> spellcheck) : spellcheck_(spellcheck) { promise_ = std::make_unique<gin_helper::Promise<std::set<std::string>>>( std::move(promise)); if (spellcheck_) spellcheck_->GetCustomDictionary()->AddObserver(this); } ~DictionaryObserver() { if (spellcheck_) spellcheck_->GetCustomDictionary()->RemoveObserver(this); } void OnCustomDictionaryLoaded() override { if (spellcheck_) { promise_->Resolve(spellcheck_->GetCustomDictionary()->GetWords()); } else { promise_->RejectWithErrorMessage( "Spellcheck in unexpected state: failed to load custom dictionary."); } delete this; } void OnCustomDictionaryChanged( const SpellcheckCustomDictionary::Change& dictionary_change) override { // noop } }; #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) struct UserDataLink : base::SupportsUserData::Data { explicit UserDataLink(Session* ses) : session(ses) {} Session* session; }; const void* kElectronApiSessionKey = &kElectronApiSessionKey; } // namespace gin::WrapperInfo Session::kWrapperInfo = {gin::kEmbedderNativeGin}; Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context) : isolate_(isolate), network_emulation_token_(base::UnguessableToken::Create()), browser_context_(browser_context) { // Observe DownloadManager to get download notifications. browser_context->GetDownloadManager()->AddObserver(this); new SessionPreferences(browser_context); protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8()); browser_context->SetUserData(kElectronApiSessionKey, std::make_unique<UserDataLink>(this)); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (service) { service->SetHunspellObserver(this); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ExtensionRegistry::Get(browser_context)->AddObserver(this); #endif } Session::~Session() { browser_context()->GetDownloadManager()->RemoveObserver(this); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (service) { service->SetHunspellObserver(nullptr); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ExtensionRegistry::Get(browser_context())->RemoveObserver(this); #endif } void Session::OnDownloadCreated(content::DownloadManager* manager, download::DownloadItem* item) { if (item->IsSavePackageDownload()) return; v8::HandleScope handle_scope(isolate_); auto handle = DownloadItem::FromOrCreate(isolate_, item); if (item->GetState() == download::DownloadItem::INTERRUPTED) handle->SetSavePath(item->GetTargetFilePath()); content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); bool prevent_default = Emit("will-download", handle, web_contents); if (prevent_default) { item->Cancel(true); item->Remove(); } } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) void Session::OnHunspellDictionaryInitialized(const std::string& language) { Emit("spellcheck-dictionary-initialized", language); } void Session::OnHunspellDictionaryDownloadBegin(const std::string& language) { Emit("spellcheck-dictionary-download-begin", language); } void Session::OnHunspellDictionaryDownloadSuccess(const std::string& language) { Emit("spellcheck-dictionary-download-success", language); } void Session::OnHunspellDictionaryDownloadFailure(const std::string& language) { Emit("spellcheck-dictionary-download-failure", language); } #endif v8::Local<v8::Promise> Session::ResolveProxy(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<std::string> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); GURL url; args->GetNext(&url); browser_context_->GetResolveProxyHelper()->ResolveProxy( url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::GetCacheSize() { gin_helper::Promise<int64_t> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ComputeHttpCacheSize( base::Time(), base::Time::Max(), base::BindOnce( [](gin_helper::Promise<int64_t> promise, bool is_upper_bound, int64_t size_or_error) { if (size_or_error < 0) { promise.RejectWithErrorMessage( net::ErrorToString(size_or_error)); } else { promise.Resolve(size_or_error); } }, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearCache() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHttpCache(base::Time(), base::Time::Max(), nullptr, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearStorageData(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); ClearStorageDataOptions options; args->GetNext(&options); auto* storage_partition = browser_context()->GetStoragePartition(nullptr); if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) { // Reset media device id salt when cookies are cleared. // https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid MediaDeviceIDSalt::Reset(browser_context()->prefs()); } storage_partition->ClearData( options.storage_types, options.quota_types, options.storage_key, base::Time(), base::Time::Max(), base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::FlushStorageData() { auto* storage_partition = browser_context()->GetStoragePartition(nullptr); storage_partition->Flush(); } v8::Local<v8::Promise> Session::SetProxy(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); gin_helper::Dictionary options; args->GetNext(&options); if (!browser_context_->in_memory_pref_store()) { promise.Resolve(); return handle; } std::string mode, proxy_rules, bypass_list, pac_url; options.Get("pacScript", &pac_url); options.Get("proxyRules", &proxy_rules); options.Get("proxyBypassRules", &bypass_list); ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS; if (!options.Get("mode", &mode)) { // pacScript takes precedence over proxyRules. if (!pac_url.empty()) { proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT; } else { proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS; } } else { if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) { promise.RejectWithErrorMessage( "Invalid mode, must be one of direct, auto_detect, pac_script, " "fixed_servers or system"); return handle; } } std::unique_ptr<base::Value> proxy_config; if (proxy_mode == ProxyPrefs::MODE_DIRECT) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreateDirect()); } else if (proxy_mode == ProxyPrefs::MODE_SYSTEM) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreateSystem()); } else if (proxy_mode == ProxyPrefs::MODE_AUTO_DETECT) { proxy_config = std::make_unique<base::Value>( ProxyConfigDictionary::CreateAutoDetect()); } else if (proxy_mode == ProxyPrefs::MODE_PAC_SCRIPT) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreatePacScript( pac_url, true /* pac_mandatory */)); } else { proxy_config = std::make_unique<base::Value>( ProxyConfigDictionary::CreateFixedServers(proxy_rules, bypass_list)); } browser_context_->in_memory_pref_store()->SetValue( proxy_config::prefs::kProxy, std::move(proxy_config), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ForceReloadProxyConfig() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ForceReloadProxyConfig(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::SetDownloadPath(const base::FilePath& path) { browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path); } void Session::EnableNetworkEmulation(const gin_helper::Dictionary& options) { auto conditions = network::mojom::NetworkConditions::New(); options.Get("offline", &conditions->offline); options.Get("downloadThroughput", &conditions->download_throughput); options.Get("uploadThroughput", &conditions->upload_throughput); double latency = 0.0; if (options.Get("latency", &latency) && latency) { conditions->latency = base::Milliseconds(latency); } auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetNetworkConditions(network_emulation_token_, std::move(conditions)); } void Session::DisableNetworkEmulation() { auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetNetworkConditions( network_emulation_token_, network::mojom::NetworkConditions::New()); } void Session::SetCertVerifyProc(v8::Local<v8::Value> val, gin::Arguments* args) { CertVerifierClient::CertVerifyProc proc; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &proc))) { args->ThrowTypeError("Must pass null or function"); return; } mojo::PendingRemote<network::mojom::CertVerifierClient> cert_verifier_client_remote; if (proc) { mojo::MakeSelfOwnedReceiver( std::make_unique<CertVerifierClient>(proc), cert_verifier_client_remote.InitWithNewPipeAndPassReceiver()); } browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->SetCertVerifierClient(std::move(cert_verifier_client_remote)); } void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val, gin::Arguments* args) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); if (val->IsNull()) { permission_manager->SetPermissionRequestHandler( ElectronPermissionManager::RequestHandler()); return; } auto handler = std::make_unique<ElectronPermissionManager::RequestHandler>(); if (!gin::ConvertFromV8(args->isolate(), val, handler.get())) { args->ThrowTypeError("Must pass null or function"); return; } permission_manager->SetPermissionRequestHandler(base::BindRepeating( [](ElectronPermissionManager::RequestHandler* handler, content::WebContents* web_contents, blink::PermissionType permission_type, ElectronPermissionManager::StatusCallback callback, const base::Value& details) { handler->Run(web_contents, permission_type, base::AdaptCallbackForRepeating(std::move(callback)), details); }, base::Owned(std::move(handler)))); } void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val, gin::Arguments* args) { ElectronPermissionManager::CheckHandler handler; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) { args->ThrowTypeError("Must pass null or function"); return; } auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); permission_manager->SetPermissionCheckHandler(handler); } void Session::SetDisplayMediaRequestHandler(v8::Isolate* isolate, v8::Local<v8::Value> val) { if (val->IsNull()) { browser_context_->SetDisplayMediaRequestHandler( DisplayMediaRequestHandler()); return; } DisplayMediaRequestHandler handler; if (!gin::ConvertFromV8(isolate, val, &handler)) { gin_helper::ErrorThrower(isolate).ThrowTypeError( "Display media request handler must be null or a function"); return; } browser_context_->SetDisplayMediaRequestHandler(handler); } void Session::SetDevicePermissionHandler(v8::Local<v8::Value> val, gin::Arguments* args) { ElectronPermissionManager::DeviceCheckHandler handler; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) { args->ThrowTypeError("Must pass null or function"); return; } auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); permission_manager->SetDevicePermissionHandler(handler); } v8::Local<v8::Promise> Session::ClearHostResolverCache(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHostCache(nullptr, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearAuthCache() { gin_helper::Promise<void> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHttpAuthCache( base::Time(), base::Time::Max(), base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::AllowNTLMCredentialsForDomains(const std::string& domains) { auto* command_line = base::CommandLine::ForCurrentProcess(); network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params = network::mojom::HttpAuthDynamicParams::New(); auth_dynamic_params->server_allowlist = domains; auth_dynamic_params->enable_negotiate_port = command_line->HasSwitch(electron::switches::kEnableAuthNegotiatePort); auth_dynamic_params->ntlm_v2_enabled = !command_line->HasSwitch(electron::switches::kDisableNTLMv2); content::GetNetworkService()->ConfigureHttpAuthPrefs( std::move(auth_dynamic_params)); } void Session::SetUserAgent(const std::string& user_agent, gin::Arguments* args) { browser_context_->SetUserAgent(user_agent); auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetUserAgent(user_agent); std::string accept_lang; if (args->GetNext(&accept_lang)) { network_context->SetAcceptLanguage( net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang)); } } std::string Session::GetUserAgent() { return browser_context_->GetUserAgent(); } void Session::SetSSLConfig(network::mojom::SSLConfigPtr config) { browser_context_->SetSSLConfig(std::move(config)); } bool Session::IsPersistent() { return !browser_context_->IsOffTheRecord(); } v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate, const std::string& uuid) { gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid); if (holder.IsEmpty()) { gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); promise.RejectWithErrorMessage("Could not get blob data handle"); return promise.GetHandle(); } return holder->ReadAll(isolate); } void Session::DownloadURL(const GURL& url) { auto* download_manager = browser_context()->GetDownloadManager(); auto download_params = std::make_unique<download::DownloadUrlParameters>( url, MISSING_TRAFFIC_ANNOTATION); download_manager->DownloadUrl(std::move(download_params)); } void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) { int64_t offset = 0, length = 0; double start_time = base::Time::Now().ToDoubleT(); std::string mime_type, last_modified, etag; base::FilePath path; std::vector<GURL> url_chain; options.Get("path", &path); options.Get("urlChain", &url_chain); options.Get("mimeType", &mime_type); options.Get("offset", &offset); options.Get("length", &length); options.Get("lastModified", &last_modified); options.Get("eTag", &etag); options.Get("startTime", &start_time); if (path.empty() || url_chain.empty() || length == 0) { isolate_->ThrowException(v8::Exception::Error(gin::StringToV8( isolate_, "Must pass non-empty path, urlChain and length."))); return; } if (offset >= length) { isolate_->ThrowException(v8::Exception::Error(gin::StringToV8( isolate_, "Must pass an offset value less than length."))); return; } auto* download_manager = browser_context()->GetDownloadManager(); download_manager->GetNextId(base::BindRepeating( &DownloadIdCallback, download_manager, path, url_chain, mime_type, offset, length, last_modified, etag, base::Time::FromDoubleT(start_time))); } void Session::SetPreloads(const std::vector<base::FilePath>& preloads) { auto* prefs = SessionPreferences::FromBrowserContext(browser_context()); DCHECK(prefs); prefs->set_preloads(preloads); } std::vector<base::FilePath> Session::GetPreloads() const { auto* prefs = SessionPreferences::FromBrowserContext(browser_context()); DCHECK(prefs); return prefs->preloads(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) v8::Local<v8::Promise> Session::LoadExtension( const base::FilePath& extension_path, gin::Arguments* args) { gin_helper::Promise<const extensions::Extension*> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!extension_path.IsAbsolute()) { promise.RejectWithErrorMessage( "The path to the extension in 'loadExtension' must be absolute"); return handle; } if (browser_context()->IsOffTheRecord()) { promise.RejectWithErrorMessage( "Extensions cannot be loaded in a temporary session"); return handle; } int load_flags = extensions::Extension::FOLLOW_SYMLINKS_ANYWHERE; gin_helper::Dictionary options; if (args->GetNext(&options)) { bool allowFileAccess = false; options.Get("allowFileAccess", &allowFileAccess); if (allowFileAccess) load_flags |= extensions::Extension::ALLOW_FILE_ACCESS; } auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(browser_context())); extension_system->LoadExtension( extension_path, load_flags, base::BindOnce( [](gin_helper::Promise<const extensions::Extension*> promise, const extensions::Extension* extension, const std::string& error_msg) { if (extension) { if (!error_msg.empty()) { node::Environment* env = node::Environment::GetCurrent(promise.isolate()); EmitWarning(env, error_msg, "ExtensionLoadWarning"); } promise.Resolve(extension); } else { promise.RejectWithErrorMessage(error_msg); } }, std::move(promise))); return handle; } void Session::RemoveExtension(const std::string& extension_id) { auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(browser_context())); extension_system->RemoveExtension(extension_id); } v8::Local<v8::Value> Session::GetExtension(const std::string& extension_id) { auto* registry = extensions::ExtensionRegistry::Get(browser_context()); const extensions::Extension* extension = registry->GetInstalledExtension(extension_id); if (extension) { return gin::ConvertToV8(isolate_, extension); } else { return v8::Null(isolate_); } } v8::Local<v8::Value> Session::GetAllExtensions() { auto* registry = extensions::ExtensionRegistry::Get(browser_context()); auto installed_extensions = registry->GenerateInstalledExtensionsSet(); std::vector<const extensions::Extension*> extensions_vector; for (const auto& extension : *installed_extensions) { if (extension->location() != extensions::mojom::ManifestLocation::kComponent) extensions_vector.emplace_back(extension.get()); } return gin::ConvertToV8(isolate_, extensions_vector); } void Session::OnExtensionLoaded(content::BrowserContext* browser_context, const extensions::Extension* extension) { Emit("extension-loaded", extension); } void Session::OnExtensionUnloaded(content::BrowserContext* browser_context, const extensions::Extension* extension, extensions::UnloadedExtensionReason reason) { Emit("extension-unloaded", extension); } void Session::OnExtensionReady(content::BrowserContext* browser_context, const extensions::Extension* extension) { Emit("extension-ready", extension); } #endif v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) { if (cookies_.IsEmpty()) { auto handle = Cookies::Create(isolate, browser_context()); cookies_.Reset(isolate, handle.ToV8()); } return cookies_.Get(isolate); } v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) { return protocol_.Get(isolate); } v8::Local<v8::Value> Session::ServiceWorkerContext(v8::Isolate* isolate) { if (service_worker_context_.IsEmpty()) { v8::Local<v8::Value> handle; handle = ServiceWorkerContext::Create(isolate, browser_context()).ToV8(); service_worker_context_.Reset(isolate, handle); } return service_worker_context_.Get(isolate); } v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) { if (web_request_.IsEmpty()) { auto handle = WebRequest::Create(isolate, browser_context()); web_request_.Reset(isolate, handle.ToV8()); } return web_request_.Get(isolate); } v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) { if (net_log_.IsEmpty()) { auto handle = NetLog::Create(isolate, browser_context()); net_log_.Reset(isolate, handle.ToV8()); } return net_log_.Get(isolate); } static void StartPreconnectOnUI(ElectronBrowserContext* browser_context, const GURL& url, int num_sockets_to_preconnect) { url::Origin origin = url::Origin::Create(url); std::vector<predictors::PreconnectRequest> requests = { {url::Origin::Create(url), num_sockets_to_preconnect, net::NetworkIsolationKey(origin, origin)}}; browser_context->GetPreconnectManager()->Start(url, requests); } void Session::Preconnect(const gin_helper::Dictionary& options, gin::Arguments* args) { GURL url; if (!options.Get("url", &url) || !url.is_valid()) { args->ThrowTypeError( "Must pass non-empty valid url to session.preconnect."); return; } int num_sockets_to_preconnect = 1; if (options.Get("numSockets", &num_sockets_to_preconnect)) { const int kMinSocketsToPreconnect = 1; const int kMaxSocketsToPreconnect = 6; if (num_sockets_to_preconnect < kMinSocketsToPreconnect || num_sockets_to_preconnect > kMaxSocketsToPreconnect) { args->ThrowTypeError( base::StringPrintf("numSocketsToPreconnect is outside range [%d,%d]", kMinSocketsToPreconnect, kMaxSocketsToPreconnect)); return; } } DCHECK_GT(num_sockets_to_preconnect, 0); content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&StartPreconnectOnUI, base::Unretained(browser_context_), url, num_sockets_to_preconnect)); } v8::Local<v8::Promise> Session::CloseAllConnections() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->CloseAllConnections(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Value> Session::GetPath(v8::Isolate* isolate) { if (browser_context_->IsOffTheRecord()) { return v8::Null(isolate); } return gin::ConvertToV8(isolate, browser_context_->GetPath()); } void Session::SetCodeCachePath(gin::Arguments* args) { base::FilePath code_cache_path; auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* code_cache_context = storage_partition->GetGeneratedCodeCacheContext(); if (code_cache_context) { if (!args->GetNext(&code_cache_path) || !code_cache_path.IsAbsolute()) { args->ThrowTypeError( "Absolute path must be provided to store code cache."); return; } code_cache_context->Initialize( code_cache_path, 0 /* allows disk_cache to choose the size */); } } v8::Local<v8::Promise> Session::ClearCodeCaches( const gin_helper::Dictionary& options) { auto* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); std::set<GURL> url_list; base::RepeatingCallback<bool(const GURL&)> url_matcher = base::NullCallback(); if (options.Get("urls", &url_list) && !url_list.empty()) { url_matcher = base::BindRepeating( [](const std::set<GURL>& url_list, const GURL& url) { return base::Contains(url_list, url); }, url_list); } browser_context_->GetDefaultStoragePartition()->ClearCodeCaches( base::Time(), base::Time::Max(), url_matcher, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value Session::GetSpellCheckerLanguages() { return browser_context_->prefs() ->GetValue(spellcheck::prefs::kSpellCheckDictionaries) .Clone(); } void Session::SetSpellCheckerLanguages( gin_helper::ErrorThrower thrower, const std::vector<std::string>& languages) { base::Value::List language_codes; for (const std::string& lang : languages) { std::string code = spellcheck::GetCorrespondingSpellCheckLanguage(lang); if (code.empty()) { thrower.ThrowError("Invalid language code provided: \"" + lang + "\" is not a valid language code"); return; } language_codes.Append(code); } browser_context_->prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); // Enable spellcheck if > 0 languages, disable if no languages set browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable, !languages.empty()); } void SetSpellCheckerDictionaryDownloadURL(gin_helper::ErrorThrower thrower, const GURL& url) { if (!url.is_valid()) { thrower.ThrowError( "The URL you provided to setSpellCheckerDictionaryDownloadURL is not a " "valid URL"); return; } SpellcheckHunspellDictionary::SetBaseDownloadURL(url); } v8::Local<v8::Promise> Session::ListWordsInSpellCheckerDictionary() { gin_helper::Promise<std::set<std::string>> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); SpellcheckService* spellcheck = SpellcheckServiceFactory::GetForContext(browser_context_); if (!spellcheck) { promise.RejectWithErrorMessage( "Spellcheck in unexpected state: failed to load custom dictionary."); return handle; } if (spellcheck->GetCustomDictionary()->IsLoaded()) { promise.Resolve(spellcheck->GetCustomDictionary()->GetWords()); } else { new DictionaryObserver(std::move(promise), spellcheck->GetWeakPtr()); // Dictionary loads by default asynchronously, // call the load function anyways just to be sure. spellcheck->GetCustomDictionary()->Load(); } return handle; } bool Session::AddWordToSpellCheckerDictionary(const std::string& word) { // don't let in-memory sessions add spellchecker words // because files will persist unintentionally bool is_in_memory = browser_context_->IsOffTheRecord(); if (is_in_memory) return false; SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (!service) return false; #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (spellcheck::UseBrowserSpellChecker()) { spellcheck_platform::AddWord(service->platform_spell_checker(), base::UTF8ToUTF16(word)); } #endif return service->GetCustomDictionary()->AddWord(word); } bool Session::RemoveWordFromSpellCheckerDictionary(const std::string& word) { // don't let in-memory sessions remove spellchecker words // because files will persist unintentionally bool is_in_memory = browser_context_->IsOffTheRecord(); if (is_in_memory) return false; SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (!service) return false; #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (spellcheck::UseBrowserSpellChecker()) { spellcheck_platform::RemoveWord(service->platform_spell_checker(), base::UTF8ToUTF16(word)); } #endif return service->GetCustomDictionary()->RemoveWord(word); } void Session::SetSpellCheckerEnabled(bool b) { browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable, b); } bool Session::IsSpellCheckerEnabled() const { return browser_context_->prefs()->GetBoolean( spellcheck::prefs::kSpellCheckEnable); } #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // static Session* Session::FromBrowserContext(content::BrowserContext* context) { auto* data = static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey)); return data ? data->session : nullptr; } // static gin::Handle<Session> Session::CreateFrom( v8::Isolate* isolate, ElectronBrowserContext* browser_context) { Session* existing = FromBrowserContext(browser_context); if (existing) return gin::CreateHandle(isolate, existing); auto handle = gin::CreateHandle(isolate, new Session(isolate, browser_context)); // The Sessions should never be garbage collected, since the common pattern is // to use partition strings, instead of using the Session object directly. handle->Pin(isolate); App::Get()->EmitCustomEvent("session-created", handle.ToV8().As<v8::Object>()); return handle; } // static gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate, const std::string& partition, base::Value::Dict options) { ElectronBrowserContext* browser_context; if (partition.empty()) { browser_context = ElectronBrowserContext::From("", false, std::move(options)); } else if (base::StartsWith(partition, kPersistPrefix, base::CompareCase::SENSITIVE)) { std::string name = partition.substr(8); browser_context = ElectronBrowserContext::From(name, false, std::move(options)); } else { browser_context = ElectronBrowserContext::From(partition, true, std::move(options)); } return CreateFrom(isolate, browser_context); } gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Session>::GetObjectTemplateBuilder( isolate) .SetMethod("resolveProxy", &Session::ResolveProxy) .SetMethod("getCacheSize", &Session::GetCacheSize) .SetMethod("clearCache", &Session::ClearCache) .SetMethod("clearStorageData", &Session::ClearStorageData) .SetMethod("flushStorageData", &Session::FlushStorageData) .SetMethod("setProxy", &Session::SetProxy) .SetMethod("forceReloadProxyConfig", &Session::ForceReloadProxyConfig) .SetMethod("setDownloadPath", &Session::SetDownloadPath) .SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation) .SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation) .SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc) .SetMethod("setPermissionRequestHandler", &Session::SetPermissionRequestHandler) .SetMethod("setPermissionCheckHandler", &Session::SetPermissionCheckHandler) .SetMethod("setDisplayMediaRequestHandler", &Session::SetDisplayMediaRequestHandler) .SetMethod("setDevicePermissionHandler", &Session::SetDevicePermissionHandler) .SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache) .SetMethod("clearAuthCache", &Session::ClearAuthCache) .SetMethod("allowNTLMCredentialsForDomains", &Session::AllowNTLMCredentialsForDomains) .SetMethod("isPersistent", &Session::IsPersistent) .SetMethod("setUserAgent", &Session::SetUserAgent) .SetMethod("getUserAgent", &Session::GetUserAgent) .SetMethod("setSSLConfig", &Session::SetSSLConfig) .SetMethod("getBlobData", &Session::GetBlobData) .SetMethod("downloadURL", &Session::DownloadURL) .SetMethod("createInterruptedDownload", &Session::CreateInterruptedDownload) .SetMethod("setPreloads", &Session::SetPreloads) .SetMethod("getPreloads", &Session::GetPreloads) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) .SetMethod("loadExtension", &Session::LoadExtension) .SetMethod("removeExtension", &Session::RemoveExtension) .SetMethod("getExtension", &Session::GetExtension) .SetMethod("getAllExtensions", &Session::GetAllExtensions) #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) .SetMethod("getSpellCheckerLanguages", &Session::GetSpellCheckerLanguages) .SetMethod("setSpellCheckerLanguages", &Session::SetSpellCheckerLanguages) .SetProperty("availableSpellCheckerLanguages", &spellcheck::SpellCheckLanguages) .SetMethod("setSpellCheckerDictionaryDownloadURL", &SetSpellCheckerDictionaryDownloadURL) .SetMethod("listWordsInSpellCheckerDictionary", &Session::ListWordsInSpellCheckerDictionary) .SetMethod("addWordToSpellCheckerDictionary", &Session::AddWordToSpellCheckerDictionary) .SetMethod("removeWordFromSpellCheckerDictionary", &Session::RemoveWordFromSpellCheckerDictionary) .SetMethod("setSpellCheckerEnabled", &Session::SetSpellCheckerEnabled) .SetMethod("isSpellCheckerEnabled", &Session::IsSpellCheckerEnabled) .SetProperty("spellCheckerEnabled", &Session::IsSpellCheckerEnabled, &Session::SetSpellCheckerEnabled) #endif .SetMethod("preconnect", &Session::Preconnect) .SetMethod("closeAllConnections", &Session::CloseAllConnections) .SetMethod("getStoragePath", &Session::GetPath) .SetMethod("setCodeCachePath", &Session::SetCodeCachePath) .SetMethod("clearCodeCaches", &Session::ClearCodeCaches) .SetProperty("cookies", &Session::Cookies) .SetProperty("netLog", &Session::NetLog) .SetProperty("protocol", &Session::Protocol) .SetProperty("serviceWorkers", &Session::ServiceWorkerContext) .SetProperty("webRequest", &Session::WebRequest) .SetProperty("storagePath", &Session::GetPath); } const char* Session::GetTypeName() { return "Session"; } } // namespace electron::api namespace { using electron::api::Session; v8::Local<v8::Value> FromPartition(const std::string& partition, gin::Arguments* args) { if (!electron::Browser::Get()->is_ready()) { args->ThrowTypeError("Session can only be received when app is ready"); return v8::Null(args->isolate()); } base::Value::Dict options; args->GetNext(&options); return Session::FromPartition(args->isolate(), partition, std::move(options)) .ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.SetMethod("fromPartition", &FromPartition); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_session, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
spec/spellchecker-spec.ts
import { BrowserWindow, Session, session } from 'electron/main'; import { expect } from 'chai'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { AddressInfo } from 'net'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { ifit, ifdescribe, delay } from './spec-helpers'; const features = process._linkedBinding('electron_common_features'); const v8Util = process._linkedBinding('electron_common_v8_util'); ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', function () { this.timeout((process.env.IS_ASAN ? 200 : 20) * 1000); let w: BrowserWindow; async function rightClick () { const contextMenuPromise = emittedOnce(w.webContents, 'context-menu'); w.webContents.sendInputEvent({ type: 'mouseDown', button: 'right', x: 43, y: 42 }); return (await contextMenuPromise)[1] as Electron.ContextMenuParams; } // When the page is just loaded, the spellchecker might not be ready yet. Since // there is no event to know the state of spellchecker, the only reliable way // to detect spellchecker is to keep checking with a busy loop. async function rightClickUntil (fn: (params: Electron.ContextMenuParams) => boolean) { const now = Date.now(); const timeout = (process.env.IS_ASAN ? 180 : 10) * 1000; let contextMenuParams = await rightClick(); while (!fn(contextMenuParams) && (Date.now() - now < timeout)) { await delay(100); contextMenuParams = await rightClick(); } return contextMenuParams; } // Setup a server to download hunspell dictionary. const server = http.createServer((req, res) => { // The provided is minimal dict for testing only, full list of words can // be found at src/third_party/hunspell_dictionaries/xx_XX.dic. fs.readFile(path.join(__dirname, '/../../third_party/hunspell_dictionaries/xx-XX-3-0.bdic'), function (err, data) { if (err) { console.error('Failed to read dictionary file'); res.writeHead(404); res.end(JSON.stringify(err)); return; } res.writeHead(200); res.end(data); }); }); before((done) => { server.listen(0, '127.0.0.1', () => done()); }); after(() => server.close()); const fixtures = path.resolve(__dirname, 'fixtures'); const preload = path.join(fixtures, 'module', 'preload-electron.js'); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { partition: `unique-spell-${Date.now()}`, contextIsolation: false, preload, sandbox } }); w.webContents.session.setSpellCheckerDictionaryDownloadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); w.webContents.session.setSpellCheckerLanguages(['en-US']); await w.loadFile(path.resolve(__dirname, './fixtures/chromium/spellchecker.html')); }); afterEach(async () => { await closeWindow(w); }); // Context menu test can not run on Windows. const shouldRun = process.platform !== 'win32'; ifit(shouldRun)('should detect correctly spelled words as correct', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typography"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.selectionText.length > 0); expect(contextMenuParams.misspelledWord).to.eq(''); expect(contextMenuParams.dictionarySuggestions).to.have.lengthOf(0); }); ifit(shouldRun)('should detect incorrectly spelled words as incorrect', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); expect(contextMenuParams.misspelledWord).to.eq('typograpy'); expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1); }); ifit(shouldRun)('should detect incorrectly spelled words as incorrect after disabling all languages and re-enabling', async () => { w.webContents.session.setSpellCheckerLanguages([]); await delay(500); w.webContents.session.setSpellCheckerLanguages(['en-US']); await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); expect(contextMenuParams.misspelledWord).to.eq('typograpy'); expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1); }); ifit(shouldRun)('should expose webFrame spellchecker correctly', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`); expect(await callWebFrameFn('isWordMisspelled("typography")')).to.equal(false); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true); expect(await callWebFrameFn('getWordSuggestions("typography")')).to.be.empty(); expect(await callWebFrameFn('getWordSuggestions("typograpy")')).to.not.be.empty(); }); describe('spellCheckerEnabled', () => { it('is enabled by default', async () => { expect(w.webContents.session.spellCheckerEnabled).to.be.true(); }); ifit(shouldRun)('can be dynamically changed', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`); w.webContents.session.spellCheckerEnabled = false; v8Util.runUntilIdle(); expect(w.webContents.session.spellCheckerEnabled).to.be.false(); // spellCheckerEnabled is sent to renderer asynchronously and there is // no event notifying when it is finished, so wait a little while to // ensure the setting has been changed in renderer. await delay(500); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(false); w.webContents.session.spellCheckerEnabled = true; v8Util.runUntilIdle(); expect(w.webContents.session.spellCheckerEnabled).to.be.true(); await delay(500); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true); }); }); describe('custom dictionary word list API', () => { let ses: Session; beforeEach(async () => { // ensure a new session runs on each test run ses = session.fromPartition(`persist:customdictionary-test-${Date.now()}`); }); afterEach(async () => { if (ses) { await ses.clearStorageData(); ses = null as any; } }); describe('ses.listWordsFromSpellCheckerDictionary', () => { it('should successfully list words in custom dictionary', async () => { const words = ['foo', 'bar', 'baz']; const results = words.map(word => ses.addWordToSpellCheckerDictionary(word)); expect(results).to.eql([true, true, true]); const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.have.deep.members(words); }); it('should return an empty array if no words are added', async () => { const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.have.length(0); }); }); describe('ses.addWordToSpellCheckerDictionary', () => { it('should successfully add word to custom dictionary', async () => { const result = ses.addWordToSpellCheckerDictionary('foobar'); expect(result).to.equal(true); const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.eql(['foobar']); }); it('should fail for an empty string', async () => { const result = ses.addWordToSpellCheckerDictionary(''); expect(result).to.equal(false); const wordList = await ses.listWordsInSpellCheckerDictionary; expect(wordList).to.have.length(0); }); // remove API will always return false because we can't add words it('should fail for non-persistent sessions', async () => { const tempSes = session.fromPartition('temporary'); const result = tempSes.addWordToSpellCheckerDictionary('foobar'); expect(result).to.equal(false); }); }); describe('ses.removeWordFromSpellCheckerDictionary', () => { it('should successfully remove words to custom dictionary', async () => { const result1 = ses.addWordToSpellCheckerDictionary('foobar'); expect(result1).to.equal(true); const wordList1 = await ses.listWordsInSpellCheckerDictionary(); expect(wordList1).to.eql(['foobar']); const result2 = ses.removeWordFromSpellCheckerDictionary('foobar'); expect(result2).to.equal(true); const wordList2 = await ses.listWordsInSpellCheckerDictionary(); expect(wordList2).to.have.length(0); }); it('should fail for words not in custom dictionary', () => { const result2 = ses.removeWordFromSpellCheckerDictionary('foobar'); expect(result2).to.equal(false); }); }); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); });
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
docs/api/session.md
# session > Manage browser sessions, cookies, cache, proxy settings, etc. Process: [Main](../glossary.md#main-process) The `session` module can be used to create new `Session` objects. You can also access the `session` of existing pages by using the `session` property of [`WebContents`](web-contents.md), or from the `session` module. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') const ses = win.webContents.session console.log(ses.getUserAgent()) ``` ## Methods The `session` module has the following methods: ### `session.fromPartition(partition[, options])` * `partition` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from `partition` string. When there is an existing `Session` with the same `partition`, it will be returned; otherwise a new `Session` instance will be created with `options`. If `partition` starts with `persist:`, the page will use a persistent session available to all pages in the app with the same `partition`. if there is no `persist:` prefix, the page will use an in-memory session. If the `partition` is empty then default session of the app will be returned. To create a `Session` with `options`, you have to ensure the `Session` with the `partition` has never been used before. There is no way to change the `options` of an existing `Session` object. ## Properties The `session` module has the following properties: ### `session.defaultSession` A `Session` object, the default session object of the app. ## Class: Session > Get and set properties of a session. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ You can create a `Session` object in the `session` module: ```javascript const { session } = require('electron') const ses = session.fromPartition('persist:name') console.log(ses.getUserAgent()) ``` ### Instance Events The following events are available on instances of `Session`: #### Event: 'will-download' Returns: * `event` Event * `item` [DownloadItem](download-item.md) * `webContents` [WebContents](web-contents.md) Emitted when Electron is about to download `item` in `webContents`. Calling `event.preventDefault()` will cancel the download and `item` will not be available from next tick of the process. ```javascript const { session } = require('electron') session.defaultSession.on('will-download', (event, item, webContents) => { event.preventDefault() require('got')(item.getURL()).then((response) => { require('fs').writeFileSync('/somewhere', response.body) }) }) ``` #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Session.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. #### Event: 'preconnect' Returns: * `event` Event * `preconnectUrl` string - The URL being requested for preconnection by the renderer. * `allowCredentials` boolean - True if the renderer is requesting that the connection include credentials (see the [spec](https://w3c.github.io/resource-hints/#preconnect) for more details.) Emitted when a render process requests preconnection to a URL, generally due to a [resource hint](https://w3c.github.io/resource-hints/). #### Event: 'spellcheck-dictionary-initialized' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully initialized. This occurs after the file has been downloaded. #### Event: 'spellcheck-dictionary-download-begin' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file starts downloading #### Event: 'spellcheck-dictionary-download-success' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file has been successfully downloaded #### Event: 'spellcheck-dictionary-download-failure' Returns: * `event` Event * `languageCode` string - The language code of the dictionary file Emitted when a hunspell dictionary file download fails. For details on the failure you should collect a netlog and inspect the download request. #### Event: 'select-hid-device' Returns: * `event` Event * `details` Object * `deviceList` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string | null (optional) Emitted when a HID device needs to be selected when a call to `navigator.hid.requestDevice` is made. `callback` should be called with `deviceId` to be selected; passing no arguments to `callback` will cancel the request. Additionally, permissioning on `navigator.hid` can be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler). ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### Event: 'hid-device-added' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a new device becomes available before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated with the newly added device. #### Event: 'hid-device-removed' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.hid.requestDevice` has been called and `select-hid-device` has fired if a device has been removed before the callback from `select-hid-device` is called. This event is intended for use when using a UI to ask users to pick a device so that the UI can be updated to remove the specified device. #### Event: 'hid-device-revoked' Returns: * `event` Event * `details` Object * `device` [HIDDevice[]](structures/hid-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `HIDDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. #### Event: 'select-serial-port' Returns: * `event` Event * `portList` [SerialPort[]](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) * `callback` Function * `portId` string Emitted when a serial port needs to be selected when a call to `navigator.serial.requestPort` is made. `callback` should be called with `portId` to be selected, passing an empty string to `callback` will cancel the request. Additionally, permissioning on `navigator.serial` can be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler) with the `serial` permission. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } return false }) win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault() const selectedPort = portList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (!selectedPort) { callback('') } else { callback(selectedPort.portId) } }) }) ``` #### Event: 'serial-port-added' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a new serial port becomes available before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated with the newly added port. #### Event: 'serial-port-removed' Returns: * `event` Event * `port` [SerialPort](structures/serial-port.md) * `webContents` [WebContents](web-contents.md) Emitted after `navigator.serial.requestPort` has been called and `select-serial-port` has fired if a serial port has been removed before the callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. ### Instance Methods The following methods are available on instances of `Session`: #### `ses.getCacheSize()` Returns `Promise<Integer>` - the session's current cache size, in bytes. #### `ses.clearCache()` Returns `Promise<void>` - resolves when the cache clear operation is complete. Clears the session’s HTTP cache. #### `ses.clearStorageData([options])` * `options` Object (optional) * `origin` string (optional) - Should follow `window.location.origin`’s representation `scheme://host:port`. * `storages` string[] (optional) - The types of storages to clear, can contain: `appcache`, `cookies`, `filesystem`, `indexdb`, `localstorage`, `shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not specified, clear all storage types. * `quotas` string[] (optional) - The types of quotas to clear, can contain: `temporary`, `persistent`, `syncable`. If not specified, clear all quotas. Returns `Promise<void>` - resolves when the storage data has been cleared. #### `ses.flushStorageData()` Writes any unwritten DOMStorage data to disk. #### `ses.setProxy(config)` * `config` Object * `mode` string (optional) - The proxy mode. Should be one of `direct`, `auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's unspecified, it will be automatically determined based on other specified options. * `direct` In direct mode all connections are created directly, without any proxy involved. * `auto_detect` In auto_detect mode the proxy configuration is determined by a PAC script that can be downloaded at http://wpad/wpad.dat. * `pac_script` In pac_script mode the proxy configuration is determined by a PAC script that is retrieved from the URL specified in the `pacScript`. This is the default mode if `pacScript` is specified. * `fixed_servers` In fixed_servers mode the proxy configuration is specified in `proxyRules`. This is the default mode if `proxyRules` is specified. * `system` In system mode the proxy configuration is taken from the operating system. Note that the system mode is different from setting no proxy configuration. In the latter case, Electron falls back to the system settings only if no command-line options influence the proxy configuration. * `pacScript` string (optional) - The URL associated with the PAC file. * `proxyRules` string (optional) - Rules indicating which proxies to use. * `proxyBypassRules` string (optional) - Rules indicating which URLs should bypass the proxy settings. Returns `Promise<void>` - Resolves when the proxy setting process is complete. Sets the proxy settings. When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules` option is ignored and `pacScript` configuration is applied. You may need `ses.closeAllConnections` to close currently in flight connections to prevent pooled sockets using previous proxy from being reused by future requests. The `proxyRules` has to follow the rules below: ```sh proxyRules = schemeProxies[";"<schemeProxies>] schemeProxies = [<urlScheme>"="]<proxyURIList> urlScheme = "http" | "https" | "ftp" | "socks" proxyURIList = <proxyURL>[","<proxyURIList>] proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>] ``` For example: * `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and HTTP proxy `foopy2:80` for `ftp://` URLs. * `foopy:80` - Use HTTP proxy `foopy:80` for all URLs. * `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing over to `bar` if `foopy:80` is unavailable, and after that using no proxy. * `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs. * `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable. * `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no proxy if `foopy` is unavailable. * `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use `socks4://foopy2` for all other URLs. The `proxyBypassRules` is a comma separated list of rules described below: * `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]` Match all hostnames that match the pattern HOSTNAME_PATTERN. Examples: "foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99", "https://x.*.y.com:99" * `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]` Match a particular domain suffix. Examples: ".google.com", ".com", "http://.google.com" * `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]` Match URLs which are IP address literals. Examples: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99" * `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS` Match any URL that is to an IP literal that falls between the given range. IP range is specified using CIDR notation. Examples: "192.168.1.1/16", "fefe:13::abc/33". * `<local>` Match local addresses. The meaning of `<local>` is whether the host matches one of: "127.0.0.1", "::1", "localhost". #### `ses.resolveProxy(url)` * `url` URL Returns `Promise<string>` - Resolves with the proxy information for `url`. #### `ses.forceReloadProxyConfig()` Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`. #### `ses.setDownloadPath(path)` * `path` string - The download location. Sets download saving directory. By default, the download directory will be the `Downloads` under the respective app folder. #### `ses.enableNetworkEmulation(options)` * `options` Object * `offline` boolean (optional) - Whether to emulate network outage. Defaults to false. * `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable latency throttling. * `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0 which will disable download throttling. * `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0 which will disable upload throttling. Emulates network with the given configuration for the `session`. ```javascript // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. window.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. window.webContents.session.enableNetworkEmulation({ offline: true }) ``` #### `ses.preconnect(options)` * `options` Object * `url` string - URL for preconnect. Only the origin is relevant for opening the socket. * `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1. Preconnects the given number of sockets to an origin. #### `ses.closeAllConnections()` Returns `Promise<void>` - Resolves when all connections are closed. **Note:** It will terminate / fail all requests currently in flight. #### `ses.disableNetworkEmulation()` Disables any network emulation already active for the `session`. Resets to the original network configuration. #### `ses.setCertificateVerifyProc(proc)` * `proc` Function | null * `request` Object * `hostname` string * `certificate` [Certificate](structures/certificate.md) * `validatedCertificate` [Certificate](structures/certificate.md) * `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`. * `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`. * `errorCode` Integer - Error code. * `callback` Function * `verificationResult` Integer - Value can be one of certificate error codes from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). Apart from the certificate error codes, the following special codes can be used. * `0` - Indicates success and disables Certificate Transparency verification. * `-2` - Indicates failure. * `-3` - Uses the verification result from chromium. Sets the certificate verify proc for `session`, the `proc` will be called with `proc(request, callback)` whenever a server certificate verification is requested. Calling `callback(0)` accepts the certificate, calling `callback(-2)` rejects it. Calling `setCertificateVerifyProc(null)` will revert back to default certificate verify proc. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.setCertificateVerifyProc((request, callback) => { const { hostname } = request if (hostname === 'github.com') { callback(0) } else { callback(-2) } }) ``` > **NOTE:** The result of this procedure is cached by the network service. #### `ses.setPermissionRequestHandler(handler)` * `handler` Function | null * `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. * `permission` string - The type of requested permission. * `clipboard-read` - Request access to read from the clipboard. * `media` - Request access to media devices such as camera, microphone and speakers. * `display-capture` - Request access to capture the screen. * `mediaKeySystem` - Request access to DRM protected content. * `geolocation` - Request access to user's current location. * `notifications` - Request notification creation and the ability to display them in the user's system tray. * `midi` - Request MIDI access in the `webmidi` API. * `midiSysex` - Request the use of system exclusive messages in the `webmidi` API. * `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. These requests always appear to originate from the main frame. * `fullscreen` - Request for the app to enter fullscreen mode. * `openExternal` - Request to open links in external applications. * `unknown` - An unrecognized permission request * `callback` Function * `permissionGranted` boolean - Allow or deny the permission. * `details` Object - Some properties are only available on certain permission types. * `externalURL` string (optional) - The url of the `openExternal` request. * `securityOrigin` string (optional) - The security origin of the `media` request. * `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video` or `audio` * `requestingUrl` string - The last URL the requesting frame loaded * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission requests for the `session`. Calling `callback(true)` will allow the permission and `callback(false)` will reject it. To clear the handler, call `setPermissionRequestHandler(null)`. Please note that you must also implement `setPermissionCheckHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. ```javascript const { session } = require('electron') session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => { if (webContents.getURL() === 'some-host' && permission === 'notifications') { return callback(false) // denied. } callback(true) }) ``` #### `ses.setPermissionCheckHandler(handler)` * `handler` Function\<boolean> | null * `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively. * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`. * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. * `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks. * `securityOrigin` string (optional) - The security origin of the `media` check. * `mediaType` string (optional) - The type of media access being requested, can be `video`, `audio` or `unknown` * `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks. * `isMainFrame` boolean - Whether the frame making the request is the main frame Sets the handler which can be used to respond to permission checks for the `session`. Returning `true` will allow the permission and `false` will reject it. Please note that you must also implement `setPermissionRequestHandler` to get complete permission handling. Most web APIs do a permission check and then make a permission request if the check is denied. To clear the handler, call `setPermissionCheckHandler(null)`. ```javascript const { session } = require('electron') const url = require('url') session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') { return true // granted } return false // denied }) ``` #### `ses.setDisplayMediaRequestHandler(handler)` * `handler` Function | null * `request` Object * `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media. * `securityOrigin` String - Origin of the page making the request. * `videoRequested` Boolean - true if the web content requested a video stream. * `audioRequested` Boolean - true if the web content requested an audio stream. * `userGesture` Boolean - Whether a user gesture was active when this request was triggered. * `callback` Function * `streams` Object * `video` Object | [WebFrameMain](web-frame-main.md) (optional) * `id` String - The id of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `name` String - The name of the stream being granted. This will usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md) object. * `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If a string is specified, can be `loopback` or `loopbackWithMute`. Specifying a loopback device will capture system audio, and is currently only supported on Windows. If a WebFrameMain is specified, will capture audio from that frame. This handler will be called when web content requests access to display media via the `navigator.mediaDevices.getDisplayMedia` API. Use the [desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant access to. ```javascript const { session, desktopCapturer } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0] }) }) }) ``` Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream will capture the video or audio stream from that frame. ```javascript const { session } = require('electron') session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { // Allow the tab to capture itself. callback({ video: request.frame }) }) ``` Passing `null` instead of a function resets the handler to its default state. #### `ses.setDevicePermissionHandler(handler)` * `handler` Function\<boolean> | null * `details` Object * `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`. * `origin` string - The origin URL of the device permission check. * `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for. Sets the handler which can be used to respond to device permission checks for the `session`. Returning `true` will allow the device to be permitted and `false` will reject it. To clear the handler, call `setDevicePermissionHandler(null)`. This handler can be used to provide default permissioning to devices without first calling for permission to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used. Additionally, the default behavior of Electron is to store granted device permision in memory. If longer term storage is needed, a developer can store granted device permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { if (permission === 'hid') { // Add logic here to determine if permission should be given to allow HID selection return true } else if (permission === 'serial') { // Add logic here to determine if permission should be given to allow serial port selection } return false }) // Optionally, retrieve previously persisted devices from a persistent store const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } // Search through the list of devices that have previously been granted permission return grantedDevices.some((grantedDevice) => { return grantedDevice.vendorId === details.device.vendorId && grantedDevice.productId === details.device.productId && grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber }) } else if (details.deviceType === 'serial') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first) return true } } return false }) win.webContents.session.on('select-hid-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) callback(selectedPort?.deviceId) }) }) ``` #### `ses.clearHostResolverCache()` Returns `Promise<void>` - Resolves when the operation is complete. Clears the host resolver cache. #### `ses.allowNTLMCredentialsForDomains(domains)` * `domains` string - A comma-separated list of servers for which integrated authentication is enabled. Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. ```javascript const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*') ``` #### `ses.setUserAgent(userAgent[, acceptLanguages])` * `userAgent` string * `acceptLanguages` string (optional) Overrides the `userAgent` and `acceptLanguages` for this session. The `acceptLanguages` must a comma separated ordered list of language codes, for example `"en-US,fr,de,ko,zh-CN,ja"`. This doesn't affect existing `WebContents`, and each `WebContents` can use `webContents.setUserAgent` to override the session-wide user agent. #### `ses.isPersistent()` Returns `boolean` - Whether or not this session is a persistent one. The default `webContents` session of a `BrowserWindow` is persistent. When creating a session from a partition, session prefixed with `persist:` will be persistent, while others will be temporary. #### `ses.getUserAgent()` Returns `string` - The user agent for this session. #### `ses.setSSLConfig(config)` * `config` Object * `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The minimum SSL version to allow when connecting to remote servers. Defaults to `tls1`. * `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version to allow when connecting to remote servers. Defaults to `tls1.3`. * `disabledCipherSuites` Integer[] (optional) - List of cipher suites which should be explicitly prevented from being used in addition to those disabled by the net built-in policy. Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is `cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but parsable cipher suites in this form will not return an error. Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002. Note that TLSv1.3 ciphers cannot be disabled using this mechanism. Sets the SSL configuration for the session. All subsequent network requests will use the new configuration. Existing network connections (such as WebSocket connections) will not be terminated, but old sockets in the pool will not be reused for new connections. #### `ses.getBlobData(identifier)` * `identifier` string - Valid UUID. Returns `Promise<Buffer>` - resolves with blob data. #### `ses.downloadURL(url)` * `url` string Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. **Note:** This does not perform any security checks that relate to a page's origin, unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl). #### `ses.createInterruptedDownload(options)` * `options` Object * `path` string - Absolute path of the download. * `urlChain` string[] - Complete URL chain for the download. * `mimeType` string (optional) * `offset` Integer - Start range for the download. * `length` Integer - Total length of the download. * `lastModified` string (optional) - Last-Modified header value. * `eTag` string (optional) - ETag header value. * `startTime` Double (optional) - Time when download was started in number of seconds since UNIX epoch. Allows resuming `cancelled` or `interrupted` downloads from previous `Session`. The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download) event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and the initial state will be `interrupted`. The download will start only when the `resume` API is called on the [DownloadItem](download-item.md). #### `ses.clearAuthCache()` Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared. #### `ses.setPreloads(preloads)` * `preloads` string[] - An array of absolute path to preload scripts Adds scripts that will be executed on ALL web contents that are associated with this session just before normal `preload` scripts run. #### `ses.getPreloads()` Returns `string[]` an array of paths to preload scripts that have been registered. #### `ses.setCodeCachePath(path)` * `path` String - Absolute path to store the v8 generated JS code cache from the renderer. Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the respective user data folder. #### `ses.clearCodeCaches(options)` * `options` Object * `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed. Returns `Promise<void>` - resolves when the code cache clear operation is complete. #### `ses.setSpellCheckerEnabled(enable)` * `enable` boolean Sets whether to enable the builtin spell checker. #### `ses.isSpellCheckerEnabled()` Returns `boolean` - Whether the builtin spell checker is enabled. #### `ses.setSpellCheckerLanguages(languages)` * `languages` string[] - An array of language codes to enable the spellchecker for. The built in spellchecker does not automatically detect what language a user is typing in. In order for the spell checker to correctly check their words you must call this API with an array of language codes. You can get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property. **Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. #### `ses.getSpellCheckerLanguages()` Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this setting with the current OS locale. This setting is persisted across restarts. **Note:** On macOS the OS spellchecker is used and has its own list of languages. This API is a no-op on macOS. #### `ses.setSpellCheckerDictionaryDownloadURL(url)` * `url` string - A base URL for Electron to download hunspell dictionaries from. By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need to host here. The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with the case it has in the ZIP file and once with the filename as all lowercase. If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic` then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`. **Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS. #### `ses.listWordsInSpellCheckerDictionary()` Returns `Promise<string[]>` - An array of all words in app's custom dictionary. Resolves when the full dictionary is loaded from disk. #### `ses.addWordToSpellCheckerDictionary(word)` * `word` string - The word you want to add to the dictionary Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well #### `ses.removeWordFromSpellCheckerDictionary(word)` * `word` string - The word you want to remove from the dictionary Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API will not work on non-persistent (in-memory) sessions. **Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well #### `ses.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise<Extension>` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('path') app.on('ready', async () => { await session.defaultSession.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. **Note:** Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error. #### `ses.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension` | `null` - The loaded extension with the given ID. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. **Note:** This API cannot be called before the `ready` event of the `app` module is emitted. #### `ses.getStoragePath()` Returns `string | null` - The absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. ### Instance Properties The following properties are available on instances of `Session`: #### `ses.availableSpellCheckerLanguages` _Readonly_ A `string[]` array which consists of all the known available spell checker languages. Providing a language code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error. #### `ses.spellCheckerEnabled` A `boolean` indicating whether builtin spell checker is enabled. #### `ses.storagePath` _Readonly_ A `string | null` indicating the absolute file system path where data for this session is persisted on disk. For in memory sessions this returns `null`. #### `ses.cookies` _Readonly_ A [`Cookies`](cookies.md) object for this session. #### `ses.serviceWorkers` _Readonly_ A [`ServiceWorkers`](service-workers.md) object for this session. #### `ses.webRequest` _Readonly_ A [`WebRequest`](web-request.md) object for this session. #### `ses.protocol` _Readonly_ A [`Protocol`](protocol.md) object for this session. ```javascript const { app, session } = require('electron') const path = require('path') app.whenReady().then(() => { const protocol = session.fromPartition('some-partition').protocol if (!protocol.registerFileProtocol('atom', (request, callback) => { const url = request.url.substr(7) callback({ path: path.normalize(`${__dirname}/${url}`) }) })) { console.error('Failed to register protocol') } }) ``` #### `ses.netLog` _Readonly_ A [`NetLog`](net-log.md) object for this session. ```javascript const { app, session } = require('electron') app.whenReady().then(async () => { const netLog = session.fromPartition('some-partition').netLog netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) }) ```
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
shell/browser/api/electron_api_session.cc
// Copyright (c) 2015 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_session.h" #include <algorithm> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "components/download/public/common/download_danger_type.h" #include "components/download/public/common/download_url_parameters.h" #include "components/prefs/pref_service.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "components/proxy_config/proxy_prefs.h" #include "content/browser/code_cache/generated_code_cache_context.h" // nogncheck #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager_delegate.h" #include "content/public/browser/network_service_instance.h" #include "content/public/browser/storage_partition.h" #include "gin/arguments.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "net/base/completion_repeating_callback.h" #include "net/base/load_flags.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_preferences.h" #include "net/http/http_cache.h" #include "net/http/http_util.h" #include "services/network/network_service.h" #include "services/network/public/cpp/features.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_cookies.h" #include "shell/browser/api/electron_api_data_pipe_holder.h" #include "shell/browser/api/electron_api_download_item.h" #include "shell/browser/api/electron_api_net_log.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_service_worker_context.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/browser.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_device_id_salt.h" #include "shell/browser/net/cert_verifier_client.h" #include "shell/browser/session_preferences.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/gurl_converter.h" #include "shell/common/gin_converters/media_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/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #include "ui/base/l10n/l10n_util.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/extension_registry.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/common/gin_converters/extension_converter.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #include "chrome/browser/spellchecker/spellcheck_service.h" // nogncheck #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) #include "components/spellcheck/browser/spellcheck_platform.h" #include "components/spellcheck/common/spellcheck_features.h" #endif #endif using content::BrowserThread; using content::StoragePartition; namespace predictors { // NOTE(nornagon): this is copied from // //chrome/browser/predictors/resource_prefetch_predictor.cc we don't need // anything in that file other than this constructor. Without it we get a link // error. Probably upstream the constructor should be moved to // preconnect_manager.cc. PreconnectRequest::PreconnectRequest( const url::Origin& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); } } // namespace predictors namespace { struct ClearStorageDataOptions { blink::StorageKey storage_key; uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL; uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL; }; uint32_t GetStorageMask(const std::vector<std::string>& storage_types) { uint32_t storage_mask = 0; for (const auto& it : storage_types) { auto type = base::ToLowerASCII(it); if (type == "cookies") storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; else if (type == "filesystem") storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; else if (type == "indexdb") storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; else if (type == "localstorage") storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; else if (type == "shadercache") storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; else if (type == "websql") storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; else if (type == "serviceworkers") storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; else if (type == "cachestorage") storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; } return storage_mask; } uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) { uint32_t quota_mask = 0; for (const auto& it : quota_types) { auto type = base::ToLowerASCII(it); if (type == "temporary") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY; else if (type == "persistent") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_PERSISTENT; else if (type == "syncable") quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE; } return quota_mask; } } // namespace namespace gin { template <> struct Converter<ClearStorageDataOptions> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, ClearStorageDataOptions* out) { gin_helper::Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; if (GURL storage_origin; options.Get("origin", &storage_origin)) out->storage_key = blink::StorageKey(url::Origin::Create(storage_origin)); std::vector<std::string> types; if (options.Get("storages", &types)) out->storage_types = GetStorageMask(types); if (options.Get("quotas", &types)) out->quota_types = GetQuotaMask(types); return true; } }; bool SSLProtocolVersionFromString(const std::string& version_str, network::mojom::SSLVersion* version) { if (version_str == switches::kSSLVersionTLSv12) { *version = network::mojom::SSLVersion::kTLS12; return true; } if (version_str == switches::kSSLVersionTLSv13) { *version = network::mojom::SSLVersion::kTLS13; return true; } return false; } template <> struct Converter<uint16_t> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, uint16_t* out) { auto maybe = val->IntegerValue(isolate->GetCurrentContext()); if (maybe.IsNothing()) return false; *out = maybe.FromJust(); return true; } }; template <> struct Converter<network::mojom::SSLConfigPtr> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, network::mojom::SSLConfigPtr* out) { gin_helper::Dictionary options; if (!ConvertFromV8(isolate, val, &options)) return false; *out = network::mojom::SSLConfig::New(); std::string version_min_str; if (options.Get("minVersion", &version_min_str)) { if (!SSLProtocolVersionFromString(version_min_str, &(*out)->version_min)) return false; } std::string version_max_str; if (options.Get("maxVersion", &version_max_str)) { if (!SSLProtocolVersionFromString(version_max_str, &(*out)->version_max) || (*out)->version_max < network::mojom::SSLVersion::kTLS12) return false; } if (options.Has("disabledCipherSuites") && !options.Get("disabledCipherSuites", &(*out)->disabled_cipher_suites)) { return false; } std::sort((*out)->disabled_cipher_suites.begin(), (*out)->disabled_cipher_suites.end()); // TODO(nornagon): also support other SSLConfig properties? return true; } }; } // namespace gin namespace electron::api { namespace { const char kPersistPrefix[] = "persist:"; void DownloadIdCallback(content::DownloadManager* download_manager, const base::FilePath& path, const std::vector<GURL>& url_chain, const std::string& mime_type, int64_t offset, int64_t length, const std::string& last_modified, const std::string& etag, const base::Time& start_time, uint32_t id) { download_manager->CreateDownloadItem( base::GenerateGUID(), id, path, path, url_chain, GURL(), content::StoragePartitionConfig::CreateDefault( download_manager->GetBrowserContext()), GURL(), GURL(), absl::nullopt, mime_type, mime_type, start_time, base::Time(), etag, last_modified, offset, length, std::string(), download::DownloadItem::INTERRUPTED, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(), false, std::vector<download::DownloadItem::ReceivedSlice>(), download::DownloadItemRerouteInfo()); } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) class DictionaryObserver final : public SpellcheckCustomDictionary::Observer { private: std::unique_ptr<gin_helper::Promise<std::set<std::string>>> promise_; base::WeakPtr<SpellcheckService> spellcheck_; public: DictionaryObserver(gin_helper::Promise<std::set<std::string>> promise, base::WeakPtr<SpellcheckService> spellcheck) : spellcheck_(spellcheck) { promise_ = std::make_unique<gin_helper::Promise<std::set<std::string>>>( std::move(promise)); if (spellcheck_) spellcheck_->GetCustomDictionary()->AddObserver(this); } ~DictionaryObserver() { if (spellcheck_) spellcheck_->GetCustomDictionary()->RemoveObserver(this); } void OnCustomDictionaryLoaded() override { if (spellcheck_) { promise_->Resolve(spellcheck_->GetCustomDictionary()->GetWords()); } else { promise_->RejectWithErrorMessage( "Spellcheck in unexpected state: failed to load custom dictionary."); } delete this; } void OnCustomDictionaryChanged( const SpellcheckCustomDictionary::Change& dictionary_change) override { // noop } }; #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) struct UserDataLink : base::SupportsUserData::Data { explicit UserDataLink(Session* ses) : session(ses) {} Session* session; }; const void* kElectronApiSessionKey = &kElectronApiSessionKey; } // namespace gin::WrapperInfo Session::kWrapperInfo = {gin::kEmbedderNativeGin}; Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context) : isolate_(isolate), network_emulation_token_(base::UnguessableToken::Create()), browser_context_(browser_context) { // Observe DownloadManager to get download notifications. browser_context->GetDownloadManager()->AddObserver(this); new SessionPreferences(browser_context); protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8()); browser_context->SetUserData(kElectronApiSessionKey, std::make_unique<UserDataLink>(this)); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (service) { service->SetHunspellObserver(this); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ExtensionRegistry::Get(browser_context)->AddObserver(this); #endif } Session::~Session() { browser_context()->GetDownloadManager()->RemoveObserver(this); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (service) { service->SetHunspellObserver(nullptr); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ExtensionRegistry::Get(browser_context())->RemoveObserver(this); #endif } void Session::OnDownloadCreated(content::DownloadManager* manager, download::DownloadItem* item) { if (item->IsSavePackageDownload()) return; v8::HandleScope handle_scope(isolate_); auto handle = DownloadItem::FromOrCreate(isolate_, item); if (item->GetState() == download::DownloadItem::INTERRUPTED) handle->SetSavePath(item->GetTargetFilePath()); content::WebContents* web_contents = content::DownloadItemUtils::GetWebContents(item); bool prevent_default = Emit("will-download", handle, web_contents); if (prevent_default) { item->Cancel(true); item->Remove(); } } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) void Session::OnHunspellDictionaryInitialized(const std::string& language) { Emit("spellcheck-dictionary-initialized", language); } void Session::OnHunspellDictionaryDownloadBegin(const std::string& language) { Emit("spellcheck-dictionary-download-begin", language); } void Session::OnHunspellDictionaryDownloadSuccess(const std::string& language) { Emit("spellcheck-dictionary-download-success", language); } void Session::OnHunspellDictionaryDownloadFailure(const std::string& language) { Emit("spellcheck-dictionary-download-failure", language); } #endif v8::Local<v8::Promise> Session::ResolveProxy(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<std::string> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); GURL url; args->GetNext(&url); browser_context_->GetResolveProxyHelper()->ResolveProxy( url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::GetCacheSize() { gin_helper::Promise<int64_t> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ComputeHttpCacheSize( base::Time(), base::Time::Max(), base::BindOnce( [](gin_helper::Promise<int64_t> promise, bool is_upper_bound, int64_t size_or_error) { if (size_or_error < 0) { promise.RejectWithErrorMessage( net::ErrorToString(size_or_error)); } else { promise.Resolve(size_or_error); } }, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearCache() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHttpCache(base::Time(), base::Time::Max(), nullptr, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearStorageData(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); ClearStorageDataOptions options; args->GetNext(&options); auto* storage_partition = browser_context()->GetStoragePartition(nullptr); if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) { // Reset media device id salt when cookies are cleared. // https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid MediaDeviceIDSalt::Reset(browser_context()->prefs()); } storage_partition->ClearData( options.storage_types, options.quota_types, options.storage_key, base::Time(), base::Time::Max(), base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::FlushStorageData() { auto* storage_partition = browser_context()->GetStoragePartition(nullptr); storage_partition->Flush(); } v8::Local<v8::Promise> Session::SetProxy(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); gin_helper::Dictionary options; args->GetNext(&options); if (!browser_context_->in_memory_pref_store()) { promise.Resolve(); return handle; } std::string mode, proxy_rules, bypass_list, pac_url; options.Get("pacScript", &pac_url); options.Get("proxyRules", &proxy_rules); options.Get("proxyBypassRules", &bypass_list); ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS; if (!options.Get("mode", &mode)) { // pacScript takes precedence over proxyRules. if (!pac_url.empty()) { proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT; } else { proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS; } } else { if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) { promise.RejectWithErrorMessage( "Invalid mode, must be one of direct, auto_detect, pac_script, " "fixed_servers or system"); return handle; } } std::unique_ptr<base::Value> proxy_config; if (proxy_mode == ProxyPrefs::MODE_DIRECT) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreateDirect()); } else if (proxy_mode == ProxyPrefs::MODE_SYSTEM) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreateSystem()); } else if (proxy_mode == ProxyPrefs::MODE_AUTO_DETECT) { proxy_config = std::make_unique<base::Value>( ProxyConfigDictionary::CreateAutoDetect()); } else if (proxy_mode == ProxyPrefs::MODE_PAC_SCRIPT) { proxy_config = std::make_unique<base::Value>(ProxyConfigDictionary::CreatePacScript( pac_url, true /* pac_mandatory */)); } else { proxy_config = std::make_unique<base::Value>( ProxyConfigDictionary::CreateFixedServers(proxy_rules, bypass_list)); } browser_context_->in_memory_pref_store()->SetValue( proxy_config::prefs::kProxy, std::move(proxy_config), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ForceReloadProxyConfig() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ForceReloadProxyConfig(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::SetDownloadPath(const base::FilePath& path) { browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path); } void Session::EnableNetworkEmulation(const gin_helper::Dictionary& options) { auto conditions = network::mojom::NetworkConditions::New(); options.Get("offline", &conditions->offline); options.Get("downloadThroughput", &conditions->download_throughput); options.Get("uploadThroughput", &conditions->upload_throughput); double latency = 0.0; if (options.Get("latency", &latency) && latency) { conditions->latency = base::Milliseconds(latency); } auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetNetworkConditions(network_emulation_token_, std::move(conditions)); } void Session::DisableNetworkEmulation() { auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetNetworkConditions( network_emulation_token_, network::mojom::NetworkConditions::New()); } void Session::SetCertVerifyProc(v8::Local<v8::Value> val, gin::Arguments* args) { CertVerifierClient::CertVerifyProc proc; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &proc))) { args->ThrowTypeError("Must pass null or function"); return; } mojo::PendingRemote<network::mojom::CertVerifierClient> cert_verifier_client_remote; if (proc) { mojo::MakeSelfOwnedReceiver( std::make_unique<CertVerifierClient>(proc), cert_verifier_client_remote.InitWithNewPipeAndPassReceiver()); } browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->SetCertVerifierClient(std::move(cert_verifier_client_remote)); } void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val, gin::Arguments* args) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); if (val->IsNull()) { permission_manager->SetPermissionRequestHandler( ElectronPermissionManager::RequestHandler()); return; } auto handler = std::make_unique<ElectronPermissionManager::RequestHandler>(); if (!gin::ConvertFromV8(args->isolate(), val, handler.get())) { args->ThrowTypeError("Must pass null or function"); return; } permission_manager->SetPermissionRequestHandler(base::BindRepeating( [](ElectronPermissionManager::RequestHandler* handler, content::WebContents* web_contents, blink::PermissionType permission_type, ElectronPermissionManager::StatusCallback callback, const base::Value& details) { handler->Run(web_contents, permission_type, base::AdaptCallbackForRepeating(std::move(callback)), details); }, base::Owned(std::move(handler)))); } void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val, gin::Arguments* args) { ElectronPermissionManager::CheckHandler handler; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) { args->ThrowTypeError("Must pass null or function"); return; } auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); permission_manager->SetPermissionCheckHandler(handler); } void Session::SetDisplayMediaRequestHandler(v8::Isolate* isolate, v8::Local<v8::Value> val) { if (val->IsNull()) { browser_context_->SetDisplayMediaRequestHandler( DisplayMediaRequestHandler()); return; } DisplayMediaRequestHandler handler; if (!gin::ConvertFromV8(isolate, val, &handler)) { gin_helper::ErrorThrower(isolate).ThrowTypeError( "Display media request handler must be null or a function"); return; } browser_context_->SetDisplayMediaRequestHandler(handler); } void Session::SetDevicePermissionHandler(v8::Local<v8::Value> val, gin::Arguments* args) { ElectronPermissionManager::DeviceCheckHandler handler; if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) { args->ThrowTypeError("Must pass null or function"); return; } auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context()->GetPermissionControllerDelegate()); permission_manager->SetDevicePermissionHandler(handler); } v8::Local<v8::Promise> Session::ClearHostResolverCache(gin::Arguments* args) { v8::Isolate* isolate = args->isolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHostCache(nullptr, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Promise> Session::ClearAuthCache() { gin_helper::Promise<void> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->ClearHttpAuthCache( base::Time(), base::Time::Max(), base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Session::AllowNTLMCredentialsForDomains(const std::string& domains) { auto* command_line = base::CommandLine::ForCurrentProcess(); network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params = network::mojom::HttpAuthDynamicParams::New(); auth_dynamic_params->server_allowlist = domains; auth_dynamic_params->enable_negotiate_port = command_line->HasSwitch(electron::switches::kEnableAuthNegotiatePort); auth_dynamic_params->ntlm_v2_enabled = !command_line->HasSwitch(electron::switches::kDisableNTLMv2); content::GetNetworkService()->ConfigureHttpAuthPrefs( std::move(auth_dynamic_params)); } void Session::SetUserAgent(const std::string& user_agent, gin::Arguments* args) { browser_context_->SetUserAgent(user_agent); auto* network_context = browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); network_context->SetUserAgent(user_agent); std::string accept_lang; if (args->GetNext(&accept_lang)) { network_context->SetAcceptLanguage( net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang)); } } std::string Session::GetUserAgent() { return browser_context_->GetUserAgent(); } void Session::SetSSLConfig(network::mojom::SSLConfigPtr config) { browser_context_->SetSSLConfig(std::move(config)); } bool Session::IsPersistent() { return !browser_context_->IsOffTheRecord(); } v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate, const std::string& uuid) { gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid); if (holder.IsEmpty()) { gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); promise.RejectWithErrorMessage("Could not get blob data handle"); return promise.GetHandle(); } return holder->ReadAll(isolate); } void Session::DownloadURL(const GURL& url) { auto* download_manager = browser_context()->GetDownloadManager(); auto download_params = std::make_unique<download::DownloadUrlParameters>( url, MISSING_TRAFFIC_ANNOTATION); download_manager->DownloadUrl(std::move(download_params)); } void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) { int64_t offset = 0, length = 0; double start_time = base::Time::Now().ToDoubleT(); std::string mime_type, last_modified, etag; base::FilePath path; std::vector<GURL> url_chain; options.Get("path", &path); options.Get("urlChain", &url_chain); options.Get("mimeType", &mime_type); options.Get("offset", &offset); options.Get("length", &length); options.Get("lastModified", &last_modified); options.Get("eTag", &etag); options.Get("startTime", &start_time); if (path.empty() || url_chain.empty() || length == 0) { isolate_->ThrowException(v8::Exception::Error(gin::StringToV8( isolate_, "Must pass non-empty path, urlChain and length."))); return; } if (offset >= length) { isolate_->ThrowException(v8::Exception::Error(gin::StringToV8( isolate_, "Must pass an offset value less than length."))); return; } auto* download_manager = browser_context()->GetDownloadManager(); download_manager->GetNextId(base::BindRepeating( &DownloadIdCallback, download_manager, path, url_chain, mime_type, offset, length, last_modified, etag, base::Time::FromDoubleT(start_time))); } void Session::SetPreloads(const std::vector<base::FilePath>& preloads) { auto* prefs = SessionPreferences::FromBrowserContext(browser_context()); DCHECK(prefs); prefs->set_preloads(preloads); } std::vector<base::FilePath> Session::GetPreloads() const { auto* prefs = SessionPreferences::FromBrowserContext(browser_context()); DCHECK(prefs); return prefs->preloads(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) v8::Local<v8::Promise> Session::LoadExtension( const base::FilePath& extension_path, gin::Arguments* args) { gin_helper::Promise<const extensions::Extension*> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!extension_path.IsAbsolute()) { promise.RejectWithErrorMessage( "The path to the extension in 'loadExtension' must be absolute"); return handle; } if (browser_context()->IsOffTheRecord()) { promise.RejectWithErrorMessage( "Extensions cannot be loaded in a temporary session"); return handle; } int load_flags = extensions::Extension::FOLLOW_SYMLINKS_ANYWHERE; gin_helper::Dictionary options; if (args->GetNext(&options)) { bool allowFileAccess = false; options.Get("allowFileAccess", &allowFileAccess); if (allowFileAccess) load_flags |= extensions::Extension::ALLOW_FILE_ACCESS; } auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(browser_context())); extension_system->LoadExtension( extension_path, load_flags, base::BindOnce( [](gin_helper::Promise<const extensions::Extension*> promise, const extensions::Extension* extension, const std::string& error_msg) { if (extension) { if (!error_msg.empty()) { node::Environment* env = node::Environment::GetCurrent(promise.isolate()); EmitWarning(env, error_msg, "ExtensionLoadWarning"); } promise.Resolve(extension); } else { promise.RejectWithErrorMessage(error_msg); } }, std::move(promise))); return handle; } void Session::RemoveExtension(const std::string& extension_id) { auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(browser_context())); extension_system->RemoveExtension(extension_id); } v8::Local<v8::Value> Session::GetExtension(const std::string& extension_id) { auto* registry = extensions::ExtensionRegistry::Get(browser_context()); const extensions::Extension* extension = registry->GetInstalledExtension(extension_id); if (extension) { return gin::ConvertToV8(isolate_, extension); } else { return v8::Null(isolate_); } } v8::Local<v8::Value> Session::GetAllExtensions() { auto* registry = extensions::ExtensionRegistry::Get(browser_context()); auto installed_extensions = registry->GenerateInstalledExtensionsSet(); std::vector<const extensions::Extension*> extensions_vector; for (const auto& extension : *installed_extensions) { if (extension->location() != extensions::mojom::ManifestLocation::kComponent) extensions_vector.emplace_back(extension.get()); } return gin::ConvertToV8(isolate_, extensions_vector); } void Session::OnExtensionLoaded(content::BrowserContext* browser_context, const extensions::Extension* extension) { Emit("extension-loaded", extension); } void Session::OnExtensionUnloaded(content::BrowserContext* browser_context, const extensions::Extension* extension, extensions::UnloadedExtensionReason reason) { Emit("extension-unloaded", extension); } void Session::OnExtensionReady(content::BrowserContext* browser_context, const extensions::Extension* extension) { Emit("extension-ready", extension); } #endif v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) { if (cookies_.IsEmpty()) { auto handle = Cookies::Create(isolate, browser_context()); cookies_.Reset(isolate, handle.ToV8()); } return cookies_.Get(isolate); } v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) { return protocol_.Get(isolate); } v8::Local<v8::Value> Session::ServiceWorkerContext(v8::Isolate* isolate) { if (service_worker_context_.IsEmpty()) { v8::Local<v8::Value> handle; handle = ServiceWorkerContext::Create(isolate, browser_context()).ToV8(); service_worker_context_.Reset(isolate, handle); } return service_worker_context_.Get(isolate); } v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) { if (web_request_.IsEmpty()) { auto handle = WebRequest::Create(isolate, browser_context()); web_request_.Reset(isolate, handle.ToV8()); } return web_request_.Get(isolate); } v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) { if (net_log_.IsEmpty()) { auto handle = NetLog::Create(isolate, browser_context()); net_log_.Reset(isolate, handle.ToV8()); } return net_log_.Get(isolate); } static void StartPreconnectOnUI(ElectronBrowserContext* browser_context, const GURL& url, int num_sockets_to_preconnect) { url::Origin origin = url::Origin::Create(url); std::vector<predictors::PreconnectRequest> requests = { {url::Origin::Create(url), num_sockets_to_preconnect, net::NetworkIsolationKey(origin, origin)}}; browser_context->GetPreconnectManager()->Start(url, requests); } void Session::Preconnect(const gin_helper::Dictionary& options, gin::Arguments* args) { GURL url; if (!options.Get("url", &url) || !url.is_valid()) { args->ThrowTypeError( "Must pass non-empty valid url to session.preconnect."); return; } int num_sockets_to_preconnect = 1; if (options.Get("numSockets", &num_sockets_to_preconnect)) { const int kMinSocketsToPreconnect = 1; const int kMaxSocketsToPreconnect = 6; if (num_sockets_to_preconnect < kMinSocketsToPreconnect || num_sockets_to_preconnect > kMaxSocketsToPreconnect) { args->ThrowTypeError( base::StringPrintf("numSocketsToPreconnect is outside range [%d,%d]", kMinSocketsToPreconnect, kMaxSocketsToPreconnect)); return; } } DCHECK_GT(num_sockets_to_preconnect, 0); content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&StartPreconnectOnUI, base::Unretained(browser_context_), url, num_sockets_to_preconnect)); } v8::Local<v8::Promise> Session::CloseAllConnections() { gin_helper::Promise<void> promise(isolate_); auto handle = promise.GetHandle(); browser_context_->GetDefaultStoragePartition() ->GetNetworkContext() ->CloseAllConnections(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } v8::Local<v8::Value> Session::GetPath(v8::Isolate* isolate) { if (browser_context_->IsOffTheRecord()) { return v8::Null(isolate); } return gin::ConvertToV8(isolate, browser_context_->GetPath()); } void Session::SetCodeCachePath(gin::Arguments* args) { base::FilePath code_cache_path; auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* code_cache_context = storage_partition->GetGeneratedCodeCacheContext(); if (code_cache_context) { if (!args->GetNext(&code_cache_path) || !code_cache_path.IsAbsolute()) { args->ThrowTypeError( "Absolute path must be provided to store code cache."); return; } code_cache_context->Initialize( code_cache_path, 0 /* allows disk_cache to choose the size */); } } v8::Local<v8::Promise> Session::ClearCodeCaches( const gin_helper::Dictionary& options) { auto* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); std::set<GURL> url_list; base::RepeatingCallback<bool(const GURL&)> url_matcher = base::NullCallback(); if (options.Get("urls", &url_list) && !url_list.empty()) { url_matcher = base::BindRepeating( [](const std::set<GURL>& url_list, const GURL& url) { return base::Contains(url_list, url); }, url_list); } browser_context_->GetDefaultStoragePartition()->ClearCodeCaches( base::Time(), base::Time::Max(), url_matcher, base::BindOnce(gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value Session::GetSpellCheckerLanguages() { return browser_context_->prefs() ->GetValue(spellcheck::prefs::kSpellCheckDictionaries) .Clone(); } void Session::SetSpellCheckerLanguages( gin_helper::ErrorThrower thrower, const std::vector<std::string>& languages) { base::Value::List language_codes; for (const std::string& lang : languages) { std::string code = spellcheck::GetCorrespondingSpellCheckLanguage(lang); if (code.empty()) { thrower.ThrowError("Invalid language code provided: \"" + lang + "\" is not a valid language code"); return; } language_codes.Append(code); } browser_context_->prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); // Enable spellcheck if > 0 languages, disable if no languages set browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable, !languages.empty()); } void SetSpellCheckerDictionaryDownloadURL(gin_helper::ErrorThrower thrower, const GURL& url) { if (!url.is_valid()) { thrower.ThrowError( "The URL you provided to setSpellCheckerDictionaryDownloadURL is not a " "valid URL"); return; } SpellcheckHunspellDictionary::SetBaseDownloadURL(url); } v8::Local<v8::Promise> Session::ListWordsInSpellCheckerDictionary() { gin_helper::Promise<std::set<std::string>> promise(isolate_); v8::Local<v8::Promise> handle = promise.GetHandle(); SpellcheckService* spellcheck = SpellcheckServiceFactory::GetForContext(browser_context_); if (!spellcheck) { promise.RejectWithErrorMessage( "Spellcheck in unexpected state: failed to load custom dictionary."); return handle; } if (spellcheck->GetCustomDictionary()->IsLoaded()) { promise.Resolve(spellcheck->GetCustomDictionary()->GetWords()); } else { new DictionaryObserver(std::move(promise), spellcheck->GetWeakPtr()); // Dictionary loads by default asynchronously, // call the load function anyways just to be sure. spellcheck->GetCustomDictionary()->Load(); } return handle; } bool Session::AddWordToSpellCheckerDictionary(const std::string& word) { // don't let in-memory sessions add spellchecker words // because files will persist unintentionally bool is_in_memory = browser_context_->IsOffTheRecord(); if (is_in_memory) return false; SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (!service) return false; #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (spellcheck::UseBrowserSpellChecker()) { spellcheck_platform::AddWord(service->platform_spell_checker(), base::UTF8ToUTF16(word)); } #endif return service->GetCustomDictionary()->AddWord(word); } bool Session::RemoveWordFromSpellCheckerDictionary(const std::string& word) { // don't let in-memory sessions remove spellchecker words // because files will persist unintentionally bool is_in_memory = browser_context_->IsOffTheRecord(); if (is_in_memory) return false; SpellcheckService* service = SpellcheckServiceFactory::GetForContext(browser_context_); if (!service) return false; #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) if (spellcheck::UseBrowserSpellChecker()) { spellcheck_platform::RemoveWord(service->platform_spell_checker(), base::UTF8ToUTF16(word)); } #endif return service->GetCustomDictionary()->RemoveWord(word); } void Session::SetSpellCheckerEnabled(bool b) { browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable, b); } bool Session::IsSpellCheckerEnabled() const { return browser_context_->prefs()->GetBoolean( spellcheck::prefs::kSpellCheckEnable); } #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) // static Session* Session::FromBrowserContext(content::BrowserContext* context) { auto* data = static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey)); return data ? data->session : nullptr; } // static gin::Handle<Session> Session::CreateFrom( v8::Isolate* isolate, ElectronBrowserContext* browser_context) { Session* existing = FromBrowserContext(browser_context); if (existing) return gin::CreateHandle(isolate, existing); auto handle = gin::CreateHandle(isolate, new Session(isolate, browser_context)); // The Sessions should never be garbage collected, since the common pattern is // to use partition strings, instead of using the Session object directly. handle->Pin(isolate); App::Get()->EmitCustomEvent("session-created", handle.ToV8().As<v8::Object>()); return handle; } // static gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate, const std::string& partition, base::Value::Dict options) { ElectronBrowserContext* browser_context; if (partition.empty()) { browser_context = ElectronBrowserContext::From("", false, std::move(options)); } else if (base::StartsWith(partition, kPersistPrefix, base::CompareCase::SENSITIVE)) { std::string name = partition.substr(8); browser_context = ElectronBrowserContext::From(name, false, std::move(options)); } else { browser_context = ElectronBrowserContext::From(partition, true, std::move(options)); } return CreateFrom(isolate, browser_context); } gin::ObjectTemplateBuilder Session::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Session>::GetObjectTemplateBuilder( isolate) .SetMethod("resolveProxy", &Session::ResolveProxy) .SetMethod("getCacheSize", &Session::GetCacheSize) .SetMethod("clearCache", &Session::ClearCache) .SetMethod("clearStorageData", &Session::ClearStorageData) .SetMethod("flushStorageData", &Session::FlushStorageData) .SetMethod("setProxy", &Session::SetProxy) .SetMethod("forceReloadProxyConfig", &Session::ForceReloadProxyConfig) .SetMethod("setDownloadPath", &Session::SetDownloadPath) .SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation) .SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation) .SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc) .SetMethod("setPermissionRequestHandler", &Session::SetPermissionRequestHandler) .SetMethod("setPermissionCheckHandler", &Session::SetPermissionCheckHandler) .SetMethod("setDisplayMediaRequestHandler", &Session::SetDisplayMediaRequestHandler) .SetMethod("setDevicePermissionHandler", &Session::SetDevicePermissionHandler) .SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache) .SetMethod("clearAuthCache", &Session::ClearAuthCache) .SetMethod("allowNTLMCredentialsForDomains", &Session::AllowNTLMCredentialsForDomains) .SetMethod("isPersistent", &Session::IsPersistent) .SetMethod("setUserAgent", &Session::SetUserAgent) .SetMethod("getUserAgent", &Session::GetUserAgent) .SetMethod("setSSLConfig", &Session::SetSSLConfig) .SetMethod("getBlobData", &Session::GetBlobData) .SetMethod("downloadURL", &Session::DownloadURL) .SetMethod("createInterruptedDownload", &Session::CreateInterruptedDownload) .SetMethod("setPreloads", &Session::SetPreloads) .SetMethod("getPreloads", &Session::GetPreloads) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) .SetMethod("loadExtension", &Session::LoadExtension) .SetMethod("removeExtension", &Session::RemoveExtension) .SetMethod("getExtension", &Session::GetExtension) .SetMethod("getAllExtensions", &Session::GetAllExtensions) #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) .SetMethod("getSpellCheckerLanguages", &Session::GetSpellCheckerLanguages) .SetMethod("setSpellCheckerLanguages", &Session::SetSpellCheckerLanguages) .SetProperty("availableSpellCheckerLanguages", &spellcheck::SpellCheckLanguages) .SetMethod("setSpellCheckerDictionaryDownloadURL", &SetSpellCheckerDictionaryDownloadURL) .SetMethod("listWordsInSpellCheckerDictionary", &Session::ListWordsInSpellCheckerDictionary) .SetMethod("addWordToSpellCheckerDictionary", &Session::AddWordToSpellCheckerDictionary) .SetMethod("removeWordFromSpellCheckerDictionary", &Session::RemoveWordFromSpellCheckerDictionary) .SetMethod("setSpellCheckerEnabled", &Session::SetSpellCheckerEnabled) .SetMethod("isSpellCheckerEnabled", &Session::IsSpellCheckerEnabled) .SetProperty("spellCheckerEnabled", &Session::IsSpellCheckerEnabled, &Session::SetSpellCheckerEnabled) #endif .SetMethod("preconnect", &Session::Preconnect) .SetMethod("closeAllConnections", &Session::CloseAllConnections) .SetMethod("getStoragePath", &Session::GetPath) .SetMethod("setCodeCachePath", &Session::SetCodeCachePath) .SetMethod("clearCodeCaches", &Session::ClearCodeCaches) .SetProperty("cookies", &Session::Cookies) .SetProperty("netLog", &Session::NetLog) .SetProperty("protocol", &Session::Protocol) .SetProperty("serviceWorkers", &Session::ServiceWorkerContext) .SetProperty("webRequest", &Session::WebRequest) .SetProperty("storagePath", &Session::GetPath); } const char* Session::GetTypeName() { return "Session"; } } // namespace electron::api namespace { using electron::api::Session; v8::Local<v8::Value> FromPartition(const std::string& partition, gin::Arguments* args) { if (!electron::Browser::Get()->is_ready()) { args->ThrowTypeError("Session can only be received when app is ready"); return v8::Null(args->isolate()); } base::Value::Dict options; args->GetNext(&options); return Session::FromPartition(args->isolate(), partition, std::move(options)) .ToV8(); } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.SetMethod("fromPartition", &FromPartition); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_session, Initialize)
closed
electron/electron
https://github.com/electron/electron
35,508
[Bug]: Spellcheck API can cause errors in macOS applications despite supposedly being a "no-op" on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.10 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.5.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The `setSpellCheckerLanguages` method should have no effect when invoked on macOS, other than possibly generating a warning that this API is not supported on macOS. ### Actual Behavior On macOS, invoking `ses.setSpellCheckerLanguages` with a language array containing one or more unsupported languages causes an error which can prevent the app from rendering. ("Unsupported languages" here means languages not supported by the Electron spellcheck API, which is not actually used on macOS.) This issue is further complicated by the fact that the `ses.getSpellCheckerLanguages` method returns the actual locale(s) that the macOS spellcheck API is checking against, regardless of whether the Electron spellcheck API supports those locales. As such, even something as seemingly innocuous as setting the spellcheck languages to the current spellcheck languages, which should be a no-op on any platform, can cause errors on macOS. ### Testcase Gist URL https://gist.github.com/71ad54ff04a1a5b8f1a3ceed905683a0 ### Additional Information The [Electron docs](https://www.electronjs.org/docs/latest/api/session#sessetspellcheckerlanguageslanguages) state the following: > Note: On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS. This issue can only be reproduced on a macOS device where the current system locale is one that the Electron spellcheck API does not support. For English-speaking users, you can accomplish this by setting your region to "India" in the "Language & Region" settings menu.
https://github.com/electron/electron/issues/35508
https://github.com/electron/electron/pull/35514
bf20aabb9ee7985d966ae6cb2e92f635a8d85a6f
38a7da692aaae01dae97e96b7a5eb648765efe33
2022-08-30T21:52:21Z
c++
2022-09-14T22:10:16Z
spec/spellchecker-spec.ts
import { BrowserWindow, Session, session } from 'electron/main'; import { expect } from 'chai'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { AddressInfo } from 'net'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { ifit, ifdescribe, delay } from './spec-helpers'; const features = process._linkedBinding('electron_common_features'); const v8Util = process._linkedBinding('electron_common_v8_util'); ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', function () { this.timeout((process.env.IS_ASAN ? 200 : 20) * 1000); let w: BrowserWindow; async function rightClick () { const contextMenuPromise = emittedOnce(w.webContents, 'context-menu'); w.webContents.sendInputEvent({ type: 'mouseDown', button: 'right', x: 43, y: 42 }); return (await contextMenuPromise)[1] as Electron.ContextMenuParams; } // When the page is just loaded, the spellchecker might not be ready yet. Since // there is no event to know the state of spellchecker, the only reliable way // to detect spellchecker is to keep checking with a busy loop. async function rightClickUntil (fn: (params: Electron.ContextMenuParams) => boolean) { const now = Date.now(); const timeout = (process.env.IS_ASAN ? 180 : 10) * 1000; let contextMenuParams = await rightClick(); while (!fn(contextMenuParams) && (Date.now() - now < timeout)) { await delay(100); contextMenuParams = await rightClick(); } return contextMenuParams; } // Setup a server to download hunspell dictionary. const server = http.createServer((req, res) => { // The provided is minimal dict for testing only, full list of words can // be found at src/third_party/hunspell_dictionaries/xx_XX.dic. fs.readFile(path.join(__dirname, '/../../third_party/hunspell_dictionaries/xx-XX-3-0.bdic'), function (err, data) { if (err) { console.error('Failed to read dictionary file'); res.writeHead(404); res.end(JSON.stringify(err)); return; } res.writeHead(200); res.end(data); }); }); before((done) => { server.listen(0, '127.0.0.1', () => done()); }); after(() => server.close()); const fixtures = path.resolve(__dirname, 'fixtures'); const preload = path.join(fixtures, 'module', 'preload-electron.js'); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { partition: `unique-spell-${Date.now()}`, contextIsolation: false, preload, sandbox } }); w.webContents.session.setSpellCheckerDictionaryDownloadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); w.webContents.session.setSpellCheckerLanguages(['en-US']); await w.loadFile(path.resolve(__dirname, './fixtures/chromium/spellchecker.html')); }); afterEach(async () => { await closeWindow(w); }); // Context menu test can not run on Windows. const shouldRun = process.platform !== 'win32'; ifit(shouldRun)('should detect correctly spelled words as correct', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typography"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.selectionText.length > 0); expect(contextMenuParams.misspelledWord).to.eq(''); expect(contextMenuParams.dictionarySuggestions).to.have.lengthOf(0); }); ifit(shouldRun)('should detect incorrectly spelled words as incorrect', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); expect(contextMenuParams.misspelledWord).to.eq('typograpy'); expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1); }); ifit(shouldRun)('should detect incorrectly spelled words as incorrect after disabling all languages and re-enabling', async () => { w.webContents.session.setSpellCheckerLanguages([]); await delay(500); w.webContents.session.setSpellCheckerLanguages(['en-US']); await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); expect(contextMenuParams.misspelledWord).to.eq('typograpy'); expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1); }); ifit(shouldRun)('should expose webFrame spellchecker correctly', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`); expect(await callWebFrameFn('isWordMisspelled("typography")')).to.equal(false); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true); expect(await callWebFrameFn('getWordSuggestions("typography")')).to.be.empty(); expect(await callWebFrameFn('getWordSuggestions("typograpy")')).to.not.be.empty(); }); describe('spellCheckerEnabled', () => { it('is enabled by default', async () => { expect(w.webContents.session.spellCheckerEnabled).to.be.true(); }); ifit(shouldRun)('can be dynamically changed', async () => { await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"'); await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()'); await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0); const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`); w.webContents.session.spellCheckerEnabled = false; v8Util.runUntilIdle(); expect(w.webContents.session.spellCheckerEnabled).to.be.false(); // spellCheckerEnabled is sent to renderer asynchronously and there is // no event notifying when it is finished, so wait a little while to // ensure the setting has been changed in renderer. await delay(500); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(false); w.webContents.session.spellCheckerEnabled = true; v8Util.runUntilIdle(); expect(w.webContents.session.spellCheckerEnabled).to.be.true(); await delay(500); expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true); }); }); describe('custom dictionary word list API', () => { let ses: Session; beforeEach(async () => { // ensure a new session runs on each test run ses = session.fromPartition(`persist:customdictionary-test-${Date.now()}`); }); afterEach(async () => { if (ses) { await ses.clearStorageData(); ses = null as any; } }); describe('ses.listWordsFromSpellCheckerDictionary', () => { it('should successfully list words in custom dictionary', async () => { const words = ['foo', 'bar', 'baz']; const results = words.map(word => ses.addWordToSpellCheckerDictionary(word)); expect(results).to.eql([true, true, true]); const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.have.deep.members(words); }); it('should return an empty array if no words are added', async () => { const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.have.length(0); }); }); describe('ses.addWordToSpellCheckerDictionary', () => { it('should successfully add word to custom dictionary', async () => { const result = ses.addWordToSpellCheckerDictionary('foobar'); expect(result).to.equal(true); const wordList = await ses.listWordsInSpellCheckerDictionary(); expect(wordList).to.eql(['foobar']); }); it('should fail for an empty string', async () => { const result = ses.addWordToSpellCheckerDictionary(''); expect(result).to.equal(false); const wordList = await ses.listWordsInSpellCheckerDictionary; expect(wordList).to.have.length(0); }); // remove API will always return false because we can't add words it('should fail for non-persistent sessions', async () => { const tempSes = session.fromPartition('temporary'); const result = tempSes.addWordToSpellCheckerDictionary('foobar'); expect(result).to.equal(false); }); }); describe('ses.removeWordFromSpellCheckerDictionary', () => { it('should successfully remove words to custom dictionary', async () => { const result1 = ses.addWordToSpellCheckerDictionary('foobar'); expect(result1).to.equal(true); const wordList1 = await ses.listWordsInSpellCheckerDictionary(); expect(wordList1).to.eql(['foobar']); const result2 = ses.removeWordFromSpellCheckerDictionary('foobar'); expect(result2).to.equal(true); const wordList2 = await ses.listWordsInSpellCheckerDictionary(); expect(wordList2).to.have.length(0); }); it('should fail for words not in custom dictionary', () => { const result2 = ses.removeWordFromSpellCheckerDictionary('foobar'); expect(result2).to.equal(false); }); }); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); });
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
build/fuses/fuses.json5
{ "_comment": "Modifying the fuse schema in any breaking way should result in the _version prop being incremented. NEVER remove a fuse or change its meaning, instead mark it as removed with 'r'", "_schema": "0 == off, 1 == on, r == removed fuse", "_version": 1, "run_as_node": "1", "cookie_encryption": "0", "node_options": "1", "node_cli_inspect": "1", "embedded_asar_integrity_validation": "0", "only_load_app_from_asar": "0" }
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
docs/tutorial/fuses.md
# Electron Fuses > Package time feature toggles ## What are fuses? For a subset of Electron functionality it makes sense to disable certain features for an entire application. For example, 99% of apps don't make use of `ELECTRON_RUN_AS_NODE`, these applications want to be able to ship a binary that is incapable of using that feature. We also don't want Electron consumers building Electron from source as that is both a massive technical challenge and has a high cost of both time and money. Fuses are the solution to this problem, at a high level they are "magic bits" in the Electron binary that can be flipped when packaging your Electron app to enable / disable certain features / restrictions. Because they are flipped at package time before you code sign your app the OS becomes responsible for ensuring those bits aren't flipped back via OS level code signing validation (Gatekeeper / App Locker). ## Current Fuses ### `runAsNode` **Default:** Enabled **@electron/fuses:** `FuseV1Options.RunAsNode` The runAsNode fuse toggles whether the `ELECTRON_RUN_AS_NODE` environment variable is respected or not. Please note that if this fuse is disabled then `process.fork` in the main process will not function as expected as it depends on this environment variable to function. ### `cookieEncryption` **Default:** Disabled **@electron/fuses:** `FuseV1Options.EnableCookieEncryption` The cookieEncryption fuse toggles whether the cookie store on disk is encrypted using OS level cryptography keys. By default the sqlite database that Chromium uses to store cookies stores the values in plaintext. If you wish to ensure your apps cookies are encrypted in the same way Chrome does then you should enable this fuse. Please note it is a one-way transition, if you enable this fuse existing unencrypted cookies will be encrypted-on-write but if you then disable the fuse again your cookie store will effectively be corrupt and useless. Most apps can safely enable this fuse. ### `nodeOptions` **Default:** Enabled **@electron/fuses:** `FuseV1Options.EnableNodeOptionsEnvironmentVariable` The nodeOptions fuse toggles whether the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) environment variable is respected or not. This environment variable can be used to pass all kinds of custom options to the Node.js runtime and isn't typically used by apps in production. Most apps can safely disable this fuse. ### `nodeCliInspect` **Default:** Enabled **@electron/fuses:** `FuseV1Options.EnableNodeCliInspectArguments` The nodeCliInspect fuse toggles whether the `--inspect`, `--inspect-brk`, etc. flags are respected or not. When disabled it also ensures that `SIGUSR1` signal does not initialize the main process inspector. Most apps can safely disable this fuse. ### `embeddedAsarIntegrityValidation` **Default:** Disabled **@electron/fuses:** `FuseV1Options.EnableEmbeddedAsarIntegrityValidation` The embeddedAsarIntegrityValidation fuse toggles an experimental feature on macOS that validates the content of the `app.asar` file when it is loaded. This feature is designed to have a minimal performance impact but may marginally slow down file reads from inside the `app.asar` archive. For more information on how to use asar integrity validation please read the [Asar Integrity](asar-integrity.md) documentation. ### `onlyLoadAppFromAsar` **Default:** Disabled **@electron/fuses:** `FuseV1Options.OnlyLoadAppFromAsar` The onlyLoadAppFromAsar fuse changes the search system that Electron uses to locate your app code. By default Electron will search in the following order `app.asar` -> `app` -> `default_app.asar`. When this fuse is enabled the search order becomes a single entry `app.asar` thus ensuring that when combined with the `embeddedAsarIntegrityValidation` fuse it is impossible to load non-validated code. ## How do I flip the fuses? ### The easy way We've made a handy module, [`@electron/fuses`](https://npmjs.com/package/@electron/fuses), to make flipping these fuses easy. Check out the README of that module for more details on usage and potential error cases. ```js require('@electron/fuses').flipFuses( // Path to electron require('electron'), // Fuses to flip { version: FuseVersion.V1, [FuseV1Options.RunAsNode]: false } ) ``` You can validate the fuses have been flipped or check the fuse status of an arbitrary Electron app using the fuses CLI. ```bash npx @electron/fuses read --app /Applications/Foo.app ``` ### The hard way #### Quick Glossary * **Fuse Wire**: A sequence of bytes in the Electron binary used to control the fuses * **Sentinel**: A static known sequence of bytes you can use to locate the fuse wire * **Fuse Schema**: The format / allowed values for the fuse wire Manually flipping fuses requires editing the Electron binary and modifying the fuse wire to be the sequence of bytes that represent the state of the fuses you want. Somewhere in the Electron binary there will be a sequence of bytes that look like this: ```text | ...binary | sentinel_bytes | fuse_version | fuse_wire_length | fuse_wire | ...binary | ``` * `sentinel_bytes` is always this exact string `dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX` * `fuse_version` is a single byte whose unsigned integer value represents the version of the fuse schema * `fuse_wire_length` is a single byte whose unsigned integer value represents the number of fuses in the following fuse wire * `fuse_wire` is a sequence of N bytes, each byte represents a single fuse and its state. * "0" (0x30) indicates the fuse is disabled * "1" (0x31) indicates the fuse is enabled * "r" (0x72) indicates the fuse has been removed and changing the byte to either 1 or 0 will have no effect. To flip a fuse you find its position in the fuse wire and change it to "0" or "1" depending on the state you'd like. You can view the current schema [here](https://github.com/electron/electron/blob/main/build/fuses/fuses.json5).
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch fix_crash_loading_non-standard_schemes_in_iframes.patch disable_optimization_guide_for_preconnect_feature.patch fix_return_v8_value_from_localframe_requestexecutescript.patch
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
patches/chromium/create_browser_v8_snapshot_file_name_fuse.patch
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
shell/app/electron_main_delegate.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/app/electron_main_delegate.h" #include <iostream> #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/mac/bundle_locations.h" #include "base/path_service.h" #include "base/strings/string_split.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "content/public/common/content_switches.h" #include "electron/buildflags/buildflags.h" #include "extensions/common/constants.h" #include "ipc/ipc_buildflags.h" #include "sandbox/policy/switches.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/command_line_args.h" #include "shell/app/electron_content_client.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_gpu_client.h" #include "shell/browser/feature_list.h" #include "shell/browser/relauncher.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "shell/renderer/electron_renderer_client.h" #include "shell/renderer/electron_sandboxed_renderer_client.h" #include "shell/utility/electron_content_utility_client.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_switches.h" #if BUILDFLAG(IS_MAC) #include "shell/app/electron_main_delegate_mac.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "chrome/child/v8_crashpad_support_win.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/nix/xdg_util.h" #include "components/crash/core/app/breakpad_linux.h" #include "v8/include/v8-wasm-trap-handler-posix.h" #include "v8/include/v8.h" #endif #if !defined(MAS_BUILD) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #include "components/crash/core/common/crash_key.h" #include "components/crash/core/common/crash_keys.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/common/crash_keys.h" #endif namespace electron { namespace { const char kRelauncherProcess[] = "relauncher"; constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX"); constexpr base::StringPiece kElectronEnableStackDumping( "ELECTRON_ENABLE_STACK_DUMPING"); bool IsBrowserProcess(base::CommandLine* cmd) { std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType); return process_type.empty(); } // Returns true if this subprocess type needs the ResourceBundle initialized // and resources loaded. bool SubprocessNeedsResourceBundle(const std::string& process_type) { return #if BUILDFLAG(IS_LINUX) // The zygote process opens the resources for the renderers. process_type == ::switches::kZygoteProcess || #endif #if BUILDFLAG(IS_MAC) // Mac needs them too for scrollbar related images and for sandbox // profiles. process_type == ::switches::kGpuProcess || #endif process_type == ::switches::kPpapiPluginProcess || process_type == ::switches::kRendererProcess || process_type == ::switches::kUtilityProcess; } #if BUILDFLAG(IS_WIN) void InvalidParameterHandler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t) { // noop. } #endif // TODO(nornagon): move path provider overriding to its own file in // shell/common bool ElectronPathProvider(int key, base::FilePath* result) { bool create_dir = false; base::FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!base::PathService::Get(DIR_APP_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); create_dir = true; break; case DIR_CRASH_DUMPS: if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crashpad")); create_dir = true; break; case chrome::DIR_APP_DICTIONARIES: // TODO(nornagon): can we just default to using Chrome's logic here? if (!base::PathService::Get(DIR_SESSION_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe("Dictionaries")); create_dir = true; break; case DIR_SESSION_DATA: // By default and for backward, equivalent to DIR_USER_DATA. return base::PathService::Get(chrome::DIR_USER_DATA, result); case DIR_USER_CACHE: { #if BUILDFLAG(IS_POSIX) int parent_key = base::DIR_CACHE; #else // On Windows, there's no OS-level centralized location for caches, so // store the cache in the app data directory. int parent_key = base::DIR_ROAMING_APP_DATA; #endif if (!base::PathService::Get(parent_key, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); create_dir = true; break; } #if BUILDFLAG(IS_LINUX) case DIR_APP_DATA: { auto env = base::Environment::Create(); cur = base::nix::GetXDGDirectory( env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir); break; } #endif #if BUILDFLAG(IS_WIN) case DIR_RECENT: if (!platform_util::GetFolderPath(DIR_RECENT, &cur)) return false; create_dir = true; break; #endif case DIR_APP_LOGS: #if BUILDFLAG(IS_MAC) if (!base::PathService::Get(base::DIR_HOME, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Library")); cur = cur.Append(FILE_PATH_LITERAL("Logs")); cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); #else if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe("logs")); #endif create_dir = true; break; default: return false; } // TODO(bauerb): http://crbug.com/259796 base::ThreadRestrictions::ScopedAllowIO allow_io; if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur)) { return false; } *result = cur; return true; } void RegisterPathProvider() { base::PathService::RegisterProvider(ElectronPathProvider, PATH_START, PATH_END); } } // namespace std::string LoadResourceBundle(const std::string& locale) { const bool initialized = ui::ResourceBundle::HasSharedInstance(); DCHECK(!initialized); // Load other resource files. base::FilePath pak_dir; #if BUILDFLAG(IS_MAC) pak_dir = base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources")); #else base::PathService::Get(base::DIR_MODULE, &pak_dir); #endif std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale( locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")), ui::kScaleFactorNone); return loaded_locale; } ElectronMainDelegate::ElectronMainDelegate() = default; ElectronMainDelegate::~ElectronMainDelegate() = default; const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = { extensions::kExtensionScheme}; const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize = std::size(kNonWildcardDomainNonPortSchemes); absl::optional<int> ElectronMainDelegate::BasicStartupComplete() { auto* command_line = base::CommandLine::ForCurrentProcess(); #if BUILDFLAG(IS_WIN) v8_crashpad_support::SetUp(); // On Windows the terminal returns immediately, so we add a new line to // prevent output in the same line as the prompt. if (IsBrowserProcess(command_line)) std::wcout << std::endl; #endif // !BUILDFLAG(IS_WIN) auto env = base::Environment::Create(); gin_helper::Locker::SetIsBrowserProcess(IsBrowserProcess(command_line)); // Enable convenient stack printing. This is enabled by default in // non-official builds. if (env->HasVar(kElectronEnableStackDumping)) base::debug::EnableInProcessStackDumping(); if (env->HasVar(kElectronDisableSandbox)) command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox); tracing_sampler_profiler_ = tracing::TracingSamplerProfiler::CreateOnMainThread(); chrome::RegisterPathProvider(); electron::RegisterPathProvider(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes( kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize); #endif #if BUILDFLAG(IS_MAC) OverrideChildProcessPath(); OverrideFrameworkBundlePath(); SetUpBundleOverrides(); #endif #if BUILDFLAG(IS_WIN) // Ignore invalid parameter errors. _set_invalid_parameter_handler(InvalidParameterHandler); // Disable the ActiveVerifier, which is used by Chrome to track possible // bugs, but no use in Electron. base::win::DisableHandleVerifier(); if (IsBrowserProcess(command_line)) base::win::PinUser32(); #endif #if BUILDFLAG(IS_LINUX) // Check for --no-sandbox parameter when running as root. if (getuid() == 0 && IsSandboxEnabled(command_line)) LOG(FATAL) << "Running as root without --" << sandbox::policy::switches::kNoSandbox << " is not supported. See https://crbug.com/638180."; #endif #if defined(MAS_BUILD) // In MAS build we are using --disable-remote-core-animation. // // According to ccameron: // If you're running with --disable-remote-core-animation, you may want to // also run with --disable-gpu-memory-buffer-compositor-resources as well. // That flag makes it so we use regular GL textures instead of IOSurfaces // for compositor resources. IOSurfaces are very heavyweight to // create/destroy, but they can be displayed directly by CoreAnimation (and // --disable-remote-core-animation makes it so we don't use this property, // so they're just heavyweight with no upside). command_line->AppendSwitch( ::switches::kDisableGpuMemoryBufferCompositorResources); #endif content_client_ = std::make_unique<ElectronContentClient>(); SetContentClient(content_client_.get()); return absl::nullopt; } void ElectronMainDelegate::PreSandboxStartup() { auto* command_line = base::CommandLine::ForCurrentProcess(); std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); base::FilePath user_data_dir = command_line->GetSwitchValuePath(::switches::kUserDataDir); if (!user_data_dir.empty()) { base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA, user_data_dir, false, true); } #if !BUILDFLAG(IS_WIN) // For windows we call InitLogging later, after the sandbox is initialized. // // On Linux, we force a "preinit" in the zygote (i.e. never log to a default // log file), because the zygote is booted prior to JS running, so it can't // know the correct user-data directory. (And, further, accessing the // application name on Linux can cause glib calls that end up spawning // threads, which if done before the zygote is booted, causes a CHECK().) logging::InitElectronLogging(*command_line, /* is_preinit = */ process_type.empty() || process_type == ::switches::kZygoteProcess); #endif #if !defined(MAS_BUILD) crash_reporter::InitializeCrashKeys(); #endif // Initialize ResourceBundle which handles files loaded from external // sources. The language should have been passed in to us from the // browser process as a command line flag. if (SubprocessNeedsResourceBundle(process_type)) { std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); LoadResourceBundle(locale); } #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !defined(MAS_BUILD)) // In the main process, we wait for JS to call crashReporter.start() before // initializing crashpad. If we're in the renderer, we want to initialize it // immediately at boot. if (!process_type.empty()) { ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, process_type); } #endif #if BUILDFLAG(IS_LINUX) // Zygote needs to call InitCrashReporter() in RunZygote(). if (process_type != ::switches::kZygoteProcess && !process_type.empty()) { ElectronCrashReporterClient::Create(); if (crash_reporter::IsCrashpadEnabled()) { if (command_line->HasSwitch( crash_reporter::switches::kCrashpadHandlerPid)) { crash_reporter::InitializeCrashpad(false, process_type); crash_reporter::SetFirstChanceExceptionHandler( v8::TryHandleWebAssemblyTrapPosix); } } else { breakpad::InitCrashReporter(process_type); } } #endif #if !defined(MAS_BUILD) crash_keys::SetCrashKeysFromCommandLine(*command_line); crash_keys::SetPlatformCrashKey(); #endif if (IsBrowserProcess(command_line)) { // Only append arguments for browser process. // Allow file:// URIs to read other file:// URIs by default. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles); #if BUILDFLAG(IS_MAC) // Enable AVFoundation. command_line->AppendSwitch("enable-avfoundation"); #endif } } void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) { #if BUILDFLAG(IS_WIN) logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ process_type.empty()); #endif } absl::optional<int> ElectronMainDelegate::PreBrowserMain() { // This is initialized early because the service manager reads some feature // flags and we need to make sure the feature list is initialized before the // service manager reads the features. InitializeFeatureList(); #if BUILDFLAG(IS_MAC) RegisterAtomCrApp(); #endif return absl::nullopt; } content::ContentBrowserClient* ElectronMainDelegate::CreateContentBrowserClient() { browser_client_ = std::make_unique<ElectronBrowserClient>(); return browser_client_.get(); } content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() { gpu_client_ = std::make_unique<ElectronGpuClient>(); return gpu_client_.get(); } content::ContentRendererClient* ElectronMainDelegate::CreateContentRendererClient() { auto* command_line = base::CommandLine::ForCurrentProcess(); if (IsSandboxEnabled(command_line)) { renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>(); } else { renderer_client_ = std::make_unique<ElectronRendererClient>(); } return renderer_client_.get(); } content::ContentUtilityClient* ElectronMainDelegate::CreateContentUtilityClient() { utility_client_ = std::make_unique<ElectronContentUtilityClient>(); return utility_client_.get(); } absl::variant<int, content::MainFunctionParams> ElectronMainDelegate::RunProcess( const std::string& process_type, content::MainFunctionParams main_function_params) { if (process_type == kRelauncherProcess) return relauncher::RelauncherMain(main_function_params); else return std::move(main_function_params); } bool ElectronMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) { return absl::holds_alternative<InvokedInChildProcess>(invoked_in); } bool ElectronMainDelegate::ShouldLockSchemeRegistry() { return false; } #if BUILDFLAG(IS_LINUX) void ElectronMainDelegate::ZygoteForked() { // Needs to be called after we have DIR_USER_DATA. BrowserMain sets // this up for the browser process in a different manner. ElectronCrashReporterClient::Create(); const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); if (crash_reporter::IsCrashpadEnabled()) { if (command_line->HasSwitch( crash_reporter::switches::kCrashpadHandlerPid)) { crash_reporter::InitializeCrashpad(false, process_type); crash_reporter::SetFirstChanceExceptionHandler( v8::TryHandleWebAssemblyTrapPosix); } } else { breakpad::InitCrashReporter(process_type); } // Reset the command line for the newly spawned process. crash_keys::SetCrashKeysFromCommandLine(*command_line); } #endif // BUILDFLAG(IS_LINUX) } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
shell/app/electron_main_delegate.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_ #define ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_ #include <memory> #include <string> #include "content/public/app/content_main_delegate.h" #include "content/public/common/content_client.h" namespace tracing { class TracingSamplerProfiler; } namespace electron { std::string LoadResourceBundle(const std::string& locale); class ElectronMainDelegate : public content::ContentMainDelegate { public: static const char* const kNonWildcardDomainNonPortSchemes[]; static const size_t kNonWildcardDomainNonPortSchemesSize; ElectronMainDelegate(); ~ElectronMainDelegate() override; // disable copy ElectronMainDelegate(const ElectronMainDelegate&) = delete; ElectronMainDelegate& operator=(const ElectronMainDelegate&) = delete; protected: // content::ContentMainDelegate: absl::optional<int> BasicStartupComplete() override; void PreSandboxStartup() override; void SandboxInitialized(const std::string& process_type) override; absl::optional<int> PreBrowserMain() override; content::ContentBrowserClient* CreateContentBrowserClient() override; content::ContentGpuClient* CreateContentGpuClient() override; content::ContentRendererClient* CreateContentRendererClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override; absl::variant<int, content::MainFunctionParams> RunProcess( const std::string& process_type, content::MainFunctionParams main_function_params) override; bool ShouldCreateFeatureList(InvokedIn invoked_in) override; bool ShouldLockSchemeRegistry() override; #if BUILDFLAG(IS_LINUX) void ZygoteForked() override; #endif private: #if BUILDFLAG(IS_MAC) void OverrideChildProcessPath(); void OverrideFrameworkBundlePath(); void SetUpBundleOverrides(); #endif std::unique_ptr<content::ContentBrowserClient> browser_client_; std::unique_ptr<content::ContentClient> content_client_; std::unique_ptr<content::ContentGpuClient> gpu_client_; std::unique_ptr<content::ContentRendererClient> renderer_client_; std::unique_ptr<content::ContentUtilityClient> utility_client_; std::unique_ptr<tracing::TracingSamplerProfiler> tracing_sampler_profiler_; }; } // namespace electron #endif // ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
build/fuses/fuses.json5
{ "_comment": "Modifying the fuse schema in any breaking way should result in the _version prop being incremented. NEVER remove a fuse or change its meaning, instead mark it as removed with 'r'", "_schema": "0 == off, 1 == on, r == removed fuse", "_version": 1, "run_as_node": "1", "cookie_encryption": "0", "node_options": "1", "node_cli_inspect": "1", "embedded_asar_integrity_validation": "0", "only_load_app_from_asar": "0" }
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
docs/tutorial/fuses.md
# Electron Fuses > Package time feature toggles ## What are fuses? For a subset of Electron functionality it makes sense to disable certain features for an entire application. For example, 99% of apps don't make use of `ELECTRON_RUN_AS_NODE`, these applications want to be able to ship a binary that is incapable of using that feature. We also don't want Electron consumers building Electron from source as that is both a massive technical challenge and has a high cost of both time and money. Fuses are the solution to this problem, at a high level they are "magic bits" in the Electron binary that can be flipped when packaging your Electron app to enable / disable certain features / restrictions. Because they are flipped at package time before you code sign your app the OS becomes responsible for ensuring those bits aren't flipped back via OS level code signing validation (Gatekeeper / App Locker). ## Current Fuses ### `runAsNode` **Default:** Enabled **@electron/fuses:** `FuseV1Options.RunAsNode` The runAsNode fuse toggles whether the `ELECTRON_RUN_AS_NODE` environment variable is respected or not. Please note that if this fuse is disabled then `process.fork` in the main process will not function as expected as it depends on this environment variable to function. ### `cookieEncryption` **Default:** Disabled **@electron/fuses:** `FuseV1Options.EnableCookieEncryption` The cookieEncryption fuse toggles whether the cookie store on disk is encrypted using OS level cryptography keys. By default the sqlite database that Chromium uses to store cookies stores the values in plaintext. If you wish to ensure your apps cookies are encrypted in the same way Chrome does then you should enable this fuse. Please note it is a one-way transition, if you enable this fuse existing unencrypted cookies will be encrypted-on-write but if you then disable the fuse again your cookie store will effectively be corrupt and useless. Most apps can safely enable this fuse. ### `nodeOptions` **Default:** Enabled **@electron/fuses:** `FuseV1Options.EnableNodeOptionsEnvironmentVariable` The nodeOptions fuse toggles whether the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#node_optionsoptions) environment variable is respected or not. This environment variable can be used to pass all kinds of custom options to the Node.js runtime and isn't typically used by apps in production. Most apps can safely disable this fuse. ### `nodeCliInspect` **Default:** Enabled **@electron/fuses:** `FuseV1Options.EnableNodeCliInspectArguments` The nodeCliInspect fuse toggles whether the `--inspect`, `--inspect-brk`, etc. flags are respected or not. When disabled it also ensures that `SIGUSR1` signal does not initialize the main process inspector. Most apps can safely disable this fuse. ### `embeddedAsarIntegrityValidation` **Default:** Disabled **@electron/fuses:** `FuseV1Options.EnableEmbeddedAsarIntegrityValidation` The embeddedAsarIntegrityValidation fuse toggles an experimental feature on macOS that validates the content of the `app.asar` file when it is loaded. This feature is designed to have a minimal performance impact but may marginally slow down file reads from inside the `app.asar` archive. For more information on how to use asar integrity validation please read the [Asar Integrity](asar-integrity.md) documentation. ### `onlyLoadAppFromAsar` **Default:** Disabled **@electron/fuses:** `FuseV1Options.OnlyLoadAppFromAsar` The onlyLoadAppFromAsar fuse changes the search system that Electron uses to locate your app code. By default Electron will search in the following order `app.asar` -> `app` -> `default_app.asar`. When this fuse is enabled the search order becomes a single entry `app.asar` thus ensuring that when combined with the `embeddedAsarIntegrityValidation` fuse it is impossible to load non-validated code. ## How do I flip the fuses? ### The easy way We've made a handy module, [`@electron/fuses`](https://npmjs.com/package/@electron/fuses), to make flipping these fuses easy. Check out the README of that module for more details on usage and potential error cases. ```js require('@electron/fuses').flipFuses( // Path to electron require('electron'), // Fuses to flip { version: FuseVersion.V1, [FuseV1Options.RunAsNode]: false } ) ``` You can validate the fuses have been flipped or check the fuse status of an arbitrary Electron app using the fuses CLI. ```bash npx @electron/fuses read --app /Applications/Foo.app ``` ### The hard way #### Quick Glossary * **Fuse Wire**: A sequence of bytes in the Electron binary used to control the fuses * **Sentinel**: A static known sequence of bytes you can use to locate the fuse wire * **Fuse Schema**: The format / allowed values for the fuse wire Manually flipping fuses requires editing the Electron binary and modifying the fuse wire to be the sequence of bytes that represent the state of the fuses you want. Somewhere in the Electron binary there will be a sequence of bytes that look like this: ```text | ...binary | sentinel_bytes | fuse_version | fuse_wire_length | fuse_wire | ...binary | ``` * `sentinel_bytes` is always this exact string `dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX` * `fuse_version` is a single byte whose unsigned integer value represents the version of the fuse schema * `fuse_wire_length` is a single byte whose unsigned integer value represents the number of fuses in the following fuse wire * `fuse_wire` is a sequence of N bytes, each byte represents a single fuse and its state. * "0" (0x30) indicates the fuse is disabled * "1" (0x31) indicates the fuse is enabled * "r" (0x72) indicates the fuse has been removed and changing the byte to either 1 or 0 will have no effect. To flip a fuse you find its position in the fuse wire and change it to "0" or "1" depending on the state you'd like. You can view the current schema [here](https://github.com/electron/electron/blob/main/build/fuses/fuses.json5).
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch fix_allow_guest_webcontents_to_enter_fullscreen.patch disable_freezing_flags_after_init_in_node.patch short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch chore_add_electron_deps_to_gitignores.patch chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch add_maximized_parameter_to_linuxui_getwindowframeprovider.patch revert_spellcheck_fully_launch_spell_check_delayed_initialization.patch add_electron_deps_to_license_credits_file.patch feat_add_set_can_resize_mutator.patch fix_revert_emulationhandler_update_functions_to_early_return.patch fix_crash_loading_non-standard_schemes_in_iframes.patch disable_optimization_guide_for_preconnect_feature.patch fix_return_v8_value_from_localframe_requestexecutescript.patch
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
patches/chromium/create_browser_v8_snapshot_file_name_fuse.patch
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
shell/app/electron_main_delegate.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/app/electron_main_delegate.h" #include <iostream> #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/mac/bundle_locations.h" #include "base/path_service.h" #include "base/strings/string_split.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "content/public/common/content_switches.h" #include "electron/buildflags/buildflags.h" #include "extensions/common/constants.h" #include "ipc/ipc_buildflags.h" #include "sandbox/policy/switches.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/command_line_args.h" #include "shell/app/electron_content_client.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_gpu_client.h" #include "shell/browser/feature_list.h" #include "shell/browser/relauncher.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "shell/renderer/electron_renderer_client.h" #include "shell/renderer/electron_sandboxed_renderer_client.h" #include "shell/utility/electron_content_utility_client.h" #include "third_party/abseil-cpp/absl/types/variant.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_switches.h" #if BUILDFLAG(IS_MAC) #include "shell/app/electron_main_delegate_mac.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "chrome/child/v8_crashpad_support_win.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/nix/xdg_util.h" #include "components/crash/core/app/breakpad_linux.h" #include "v8/include/v8-wasm-trap-handler-posix.h" #include "v8/include/v8.h" #endif #if !defined(MAS_BUILD) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #include "components/crash/core/common/crash_key.h" #include "components/crash/core/common/crash_keys.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/common/crash_keys.h" #endif namespace electron { namespace { const char kRelauncherProcess[] = "relauncher"; constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX"); constexpr base::StringPiece kElectronEnableStackDumping( "ELECTRON_ENABLE_STACK_DUMPING"); bool IsBrowserProcess(base::CommandLine* cmd) { std::string process_type = cmd->GetSwitchValueASCII(::switches::kProcessType); return process_type.empty(); } // Returns true if this subprocess type needs the ResourceBundle initialized // and resources loaded. bool SubprocessNeedsResourceBundle(const std::string& process_type) { return #if BUILDFLAG(IS_LINUX) // The zygote process opens the resources for the renderers. process_type == ::switches::kZygoteProcess || #endif #if BUILDFLAG(IS_MAC) // Mac needs them too for scrollbar related images and for sandbox // profiles. process_type == ::switches::kGpuProcess || #endif process_type == ::switches::kPpapiPluginProcess || process_type == ::switches::kRendererProcess || process_type == ::switches::kUtilityProcess; } #if BUILDFLAG(IS_WIN) void InvalidParameterHandler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t) { // noop. } #endif // TODO(nornagon): move path provider overriding to its own file in // shell/common bool ElectronPathProvider(int key, base::FilePath* result) { bool create_dir = false; base::FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!base::PathService::Get(DIR_APP_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); create_dir = true; break; case DIR_CRASH_DUMPS: if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crashpad")); create_dir = true; break; case chrome::DIR_APP_DICTIONARIES: // TODO(nornagon): can we just default to using Chrome's logic here? if (!base::PathService::Get(DIR_SESSION_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe("Dictionaries")); create_dir = true; break; case DIR_SESSION_DATA: // By default and for backward, equivalent to DIR_USER_DATA. return base::PathService::Get(chrome::DIR_USER_DATA, result); case DIR_USER_CACHE: { #if BUILDFLAG(IS_POSIX) int parent_key = base::DIR_CACHE; #else // On Windows, there's no OS-level centralized location for caches, so // store the cache in the app data directory. int parent_key = base::DIR_ROAMING_APP_DATA; #endif if (!base::PathService::Get(parent_key, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); create_dir = true; break; } #if BUILDFLAG(IS_LINUX) case DIR_APP_DATA: { auto env = base::Environment::Create(); cur = base::nix::GetXDGDirectory( env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir); break; } #endif #if BUILDFLAG(IS_WIN) case DIR_RECENT: if (!platform_util::GetFolderPath(DIR_RECENT, &cur)) return false; create_dir = true; break; #endif case DIR_APP_LOGS: #if BUILDFLAG(IS_MAC) if (!base::PathService::Get(base::DIR_HOME, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Library")); cur = cur.Append(FILE_PATH_LITERAL("Logs")); cur = cur.Append(base::FilePath::FromUTF8Unsafe( GetPossiblyOverriddenApplicationName())); #else if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(base::FilePath::FromUTF8Unsafe("logs")); #endif create_dir = true; break; default: return false; } // TODO(bauerb): http://crbug.com/259796 base::ThreadRestrictions::ScopedAllowIO allow_io; if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur)) { return false; } *result = cur; return true; } void RegisterPathProvider() { base::PathService::RegisterProvider(ElectronPathProvider, PATH_START, PATH_END); } } // namespace std::string LoadResourceBundle(const std::string& locale) { const bool initialized = ui::ResourceBundle::HasSharedInstance(); DCHECK(!initialized); // Load other resource files. base::FilePath pak_dir; #if BUILDFLAG(IS_MAC) pak_dir = base::mac::FrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources")); #else base::PathService::Get(base::DIR_MODULE, &pak_dir); #endif std::string loaded_locale = ui::ResourceBundle::InitSharedInstanceWithLocale( locale, nullptr, ui::ResourceBundle::LOAD_COMMON_RESOURCES); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); bundle.AddDataPackFromPath(pak_dir.Append(FILE_PATH_LITERAL("resources.pak")), ui::kScaleFactorNone); return loaded_locale; } ElectronMainDelegate::ElectronMainDelegate() = default; ElectronMainDelegate::~ElectronMainDelegate() = default; const char* const ElectronMainDelegate::kNonWildcardDomainNonPortSchemes[] = { extensions::kExtensionScheme}; const size_t ElectronMainDelegate::kNonWildcardDomainNonPortSchemesSize = std::size(kNonWildcardDomainNonPortSchemes); absl::optional<int> ElectronMainDelegate::BasicStartupComplete() { auto* command_line = base::CommandLine::ForCurrentProcess(); #if BUILDFLAG(IS_WIN) v8_crashpad_support::SetUp(); // On Windows the terminal returns immediately, so we add a new line to // prevent output in the same line as the prompt. if (IsBrowserProcess(command_line)) std::wcout << std::endl; #endif // !BUILDFLAG(IS_WIN) auto env = base::Environment::Create(); gin_helper::Locker::SetIsBrowserProcess(IsBrowserProcess(command_line)); // Enable convenient stack printing. This is enabled by default in // non-official builds. if (env->HasVar(kElectronEnableStackDumping)) base::debug::EnableInProcessStackDumping(); if (env->HasVar(kElectronDisableSandbox)) command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox); tracing_sampler_profiler_ = tracing::TracingSamplerProfiler::CreateOnMainThread(); chrome::RegisterPathProvider(); electron::RegisterPathProvider(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) ContentSettingsPattern::SetNonWildcardDomainNonPortSchemes( kNonWildcardDomainNonPortSchemes, kNonWildcardDomainNonPortSchemesSize); #endif #if BUILDFLAG(IS_MAC) OverrideChildProcessPath(); OverrideFrameworkBundlePath(); SetUpBundleOverrides(); #endif #if BUILDFLAG(IS_WIN) // Ignore invalid parameter errors. _set_invalid_parameter_handler(InvalidParameterHandler); // Disable the ActiveVerifier, which is used by Chrome to track possible // bugs, but no use in Electron. base::win::DisableHandleVerifier(); if (IsBrowserProcess(command_line)) base::win::PinUser32(); #endif #if BUILDFLAG(IS_LINUX) // Check for --no-sandbox parameter when running as root. if (getuid() == 0 && IsSandboxEnabled(command_line)) LOG(FATAL) << "Running as root without --" << sandbox::policy::switches::kNoSandbox << " is not supported. See https://crbug.com/638180."; #endif #if defined(MAS_BUILD) // In MAS build we are using --disable-remote-core-animation. // // According to ccameron: // If you're running with --disable-remote-core-animation, you may want to // also run with --disable-gpu-memory-buffer-compositor-resources as well. // That flag makes it so we use regular GL textures instead of IOSurfaces // for compositor resources. IOSurfaces are very heavyweight to // create/destroy, but they can be displayed directly by CoreAnimation (and // --disable-remote-core-animation makes it so we don't use this property, // so they're just heavyweight with no upside). command_line->AppendSwitch( ::switches::kDisableGpuMemoryBufferCompositorResources); #endif content_client_ = std::make_unique<ElectronContentClient>(); SetContentClient(content_client_.get()); return absl::nullopt; } void ElectronMainDelegate::PreSandboxStartup() { auto* command_line = base::CommandLine::ForCurrentProcess(); std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); base::FilePath user_data_dir = command_line->GetSwitchValuePath(::switches::kUserDataDir); if (!user_data_dir.empty()) { base::PathService::OverrideAndCreateIfNeeded(chrome::DIR_USER_DATA, user_data_dir, false, true); } #if !BUILDFLAG(IS_WIN) // For windows we call InitLogging later, after the sandbox is initialized. // // On Linux, we force a "preinit" in the zygote (i.e. never log to a default // log file), because the zygote is booted prior to JS running, so it can't // know the correct user-data directory. (And, further, accessing the // application name on Linux can cause glib calls that end up spawning // threads, which if done before the zygote is booted, causes a CHECK().) logging::InitElectronLogging(*command_line, /* is_preinit = */ process_type.empty() || process_type == ::switches::kZygoteProcess); #endif #if !defined(MAS_BUILD) crash_reporter::InitializeCrashKeys(); #endif // Initialize ResourceBundle which handles files loaded from external // sources. The language should have been passed in to us from the // browser process as a command line flag. if (SubprocessNeedsResourceBundle(process_type)) { std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); LoadResourceBundle(locale); } #if BUILDFLAG(IS_WIN) || (BUILDFLAG(IS_MAC) && !defined(MAS_BUILD)) // In the main process, we wait for JS to call crashReporter.start() before // initializing crashpad. If we're in the renderer, we want to initialize it // immediately at boot. if (!process_type.empty()) { ElectronCrashReporterClient::Create(); crash_reporter::InitializeCrashpad(false, process_type); } #endif #if BUILDFLAG(IS_LINUX) // Zygote needs to call InitCrashReporter() in RunZygote(). if (process_type != ::switches::kZygoteProcess && !process_type.empty()) { ElectronCrashReporterClient::Create(); if (crash_reporter::IsCrashpadEnabled()) { if (command_line->HasSwitch( crash_reporter::switches::kCrashpadHandlerPid)) { crash_reporter::InitializeCrashpad(false, process_type); crash_reporter::SetFirstChanceExceptionHandler( v8::TryHandleWebAssemblyTrapPosix); } } else { breakpad::InitCrashReporter(process_type); } } #endif #if !defined(MAS_BUILD) crash_keys::SetCrashKeysFromCommandLine(*command_line); crash_keys::SetPlatformCrashKey(); #endif if (IsBrowserProcess(command_line)) { // Only append arguments for browser process. // Allow file:// URIs to read other file:// URIs by default. command_line->AppendSwitch(::switches::kAllowFileAccessFromFiles); #if BUILDFLAG(IS_MAC) // Enable AVFoundation. command_line->AppendSwitch("enable-avfoundation"); #endif } } void ElectronMainDelegate::SandboxInitialized(const std::string& process_type) { #if BUILDFLAG(IS_WIN) logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ process_type.empty()); #endif } absl::optional<int> ElectronMainDelegate::PreBrowserMain() { // This is initialized early because the service manager reads some feature // flags and we need to make sure the feature list is initialized before the // service manager reads the features. InitializeFeatureList(); #if BUILDFLAG(IS_MAC) RegisterAtomCrApp(); #endif return absl::nullopt; } content::ContentBrowserClient* ElectronMainDelegate::CreateContentBrowserClient() { browser_client_ = std::make_unique<ElectronBrowserClient>(); return browser_client_.get(); } content::ContentGpuClient* ElectronMainDelegate::CreateContentGpuClient() { gpu_client_ = std::make_unique<ElectronGpuClient>(); return gpu_client_.get(); } content::ContentRendererClient* ElectronMainDelegate::CreateContentRendererClient() { auto* command_line = base::CommandLine::ForCurrentProcess(); if (IsSandboxEnabled(command_line)) { renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>(); } else { renderer_client_ = std::make_unique<ElectronRendererClient>(); } return renderer_client_.get(); } content::ContentUtilityClient* ElectronMainDelegate::CreateContentUtilityClient() { utility_client_ = std::make_unique<ElectronContentUtilityClient>(); return utility_client_.get(); } absl::variant<int, content::MainFunctionParams> ElectronMainDelegate::RunProcess( const std::string& process_type, content::MainFunctionParams main_function_params) { if (process_type == kRelauncherProcess) return relauncher::RelauncherMain(main_function_params); else return std::move(main_function_params); } bool ElectronMainDelegate::ShouldCreateFeatureList(InvokedIn invoked_in) { return absl::holds_alternative<InvokedInChildProcess>(invoked_in); } bool ElectronMainDelegate::ShouldLockSchemeRegistry() { return false; } #if BUILDFLAG(IS_LINUX) void ElectronMainDelegate::ZygoteForked() { // Needs to be called after we have DIR_USER_DATA. BrowserMain sets // this up for the browser process in a different manner. ElectronCrashReporterClient::Create(); const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); if (crash_reporter::IsCrashpadEnabled()) { if (command_line->HasSwitch( crash_reporter::switches::kCrashpadHandlerPid)) { crash_reporter::InitializeCrashpad(false, process_type); crash_reporter::SetFirstChanceExceptionHandler( v8::TryHandleWebAssemblyTrapPosix); } } else { breakpad::InitCrashReporter(process_type); } // Reset the command line for the newly spawned process. crash_keys::SetCrashKeysFromCommandLine(*command_line); } #endif // BUILDFLAG(IS_LINUX) } // namespace electron
closed
electron/electron
https://github.com/electron/electron
35,170
[Feature Request]: Allow custom v8 snapshots to be used in the main process and the default snapshot in the browser process
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description We are using `electron-mksnapshot` to generate a custom v8 snapshot for our application that is desired to run **only in the main process**, not the renderer process. While debugging our app, we noticed that the snapshot is available to the renderer process **even with nodeIntegration disabled**. We noticed that electron is [patching](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) chromium to always load the v8 snapshots, with a comment indicating that this is required. Is loading the v8 snapshot required even when nodeIntegration is disabled? We would like for there to be a way to use our custom snapshot in the main process but use the default snapshot (or no snapshot with nodeIntegration disabled) in the browser process. ### Proposed Solution This could be done a variety of ways, but one possibility would be to update the [patch](https://github.com/electron/electron/blob/main/patches/chromium/load_v8_snapshot_in_browser_process.patch?rgh-link-date=2022-08-02T00%3A24%3A21Z) to not load the custom snapshot when node integration is disabled. Or if it's desired sometimes to have node integration disabled **and** a v8 snapshot included, you could have an additional parameter that specifies as such. ### Alternatives Considered One alternative for us would be to have separate main electron processes: one for the bulk of our main code that uses the snapshot, and one to purely launch the browser that doesn't launch the snapshot. This is undesirable as it significantly complicates the code and potentially bloats the size of our binary. ### Additional Information _No response_
https://github.com/electron/electron/issues/35170
https://github.com/electron/electron/pull/35266
5cf15cdab7f3d055a225dbc50c53d62614250468
f25c87dc7024397526bbe221efdaa0260392c243
2022-08-02T00:24:21Z
c++
2022-09-15T20:21:16Z
shell/app/electron_main_delegate.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_ #define ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_ #include <memory> #include <string> #include "content/public/app/content_main_delegate.h" #include "content/public/common/content_client.h" namespace tracing { class TracingSamplerProfiler; } namespace electron { std::string LoadResourceBundle(const std::string& locale); class ElectronMainDelegate : public content::ContentMainDelegate { public: static const char* const kNonWildcardDomainNonPortSchemes[]; static const size_t kNonWildcardDomainNonPortSchemesSize; ElectronMainDelegate(); ~ElectronMainDelegate() override; // disable copy ElectronMainDelegate(const ElectronMainDelegate&) = delete; ElectronMainDelegate& operator=(const ElectronMainDelegate&) = delete; protected: // content::ContentMainDelegate: absl::optional<int> BasicStartupComplete() override; void PreSandboxStartup() override; void SandboxInitialized(const std::string& process_type) override; absl::optional<int> PreBrowserMain() override; content::ContentBrowserClient* CreateContentBrowserClient() override; content::ContentGpuClient* CreateContentGpuClient() override; content::ContentRendererClient* CreateContentRendererClient() override; content::ContentUtilityClient* CreateContentUtilityClient() override; absl::variant<int, content::MainFunctionParams> RunProcess( const std::string& process_type, content::MainFunctionParams main_function_params) override; bool ShouldCreateFeatureList(InvokedIn invoked_in) override; bool ShouldLockSchemeRegistry() override; #if BUILDFLAG(IS_LINUX) void ZygoteForked() override; #endif private: #if BUILDFLAG(IS_MAC) void OverrideChildProcessPath(); void OverrideFrameworkBundlePath(); void SetUpBundleOverrides(); #endif std::unique_ptr<content::ContentBrowserClient> browser_client_; std::unique_ptr<content::ContentClient> content_client_; std::unique_ptr<content::ContentGpuClient> gpu_client_; std::unique_ptr<content::ContentRendererClient> renderer_client_; std::unique_ptr<content::ContentUtilityClient> utility_client_; std::unique_ptr<tracing::TracingSamplerProfiler> tracing_sampler_profiler_; }; } // namespace electron #endif // ELECTRON_SHELL_APP_ELECTRON_MAIN_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
35,219
[Bug]: Win7 can't open electron app after upgrade to v19.x.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x.x ### What operating system are you using? Windows ### Operating System Version win7 ### What arch are you using? x64 ### Last Known Working Electron version 17.x.x ### Expected Behavior Can open and work. ### Actual Behavior Can not open program in win7 operate system. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35219
https://github.com/electron/electron/pull/35702
fa3cd1747556b66a3e714f99e988e47334187e44
7d3f22dd32365d5432583d936fa4c7f3d480ef45
2022-08-04T08:54:15Z
c++
2022-09-16T05:33:01Z
patches/node/fix_crash_caused_by_gethostnamew_on_windows_7.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Fri, 12 Nov 2021 17:25:37 +0900 Subject: fix: crash caused by GetHostNameW on Windows 7 Backported from https://github.com/libuv/libuv/pull/3285. diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 33e874ac442f88b58d2b68c8ec9764f6f664552e..2d4cc0aaa02e61bf359e80eca27527efb49fd85e 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -37,6 +37,7 @@ #include <psapi.h> #include <tlhelp32.h> #include <windows.h> +#include <svcguid.h> /* clang-format on */ #include <userenv.h> #include <math.h> @@ -56,6 +57,10 @@ /* The number of nanoseconds in one second. */ #define UV__NANOSEC 1000000000 +/* Local buffer size for WSAQUERYSETW data inside uv__gethostnamew_nt60 + sizeof(WSAQUERYSETW) + 512 = 632 bytes to match GetHostNameW behavior */ +#define WSAQ_LOCAL_BUF_LEN (sizeof(WSAQUERYSETW) + 512) + /* Max user name length, from iphlpapi.h */ #ifndef UNLEN # define UNLEN 256 @@ -72,6 +77,11 @@ static CRITICAL_SECTION process_title_lock; /* Frequency of the high-resolution clock. */ static uint64_t hrtime_frequency_ = 0; +/* Parameters for WSAQUERYSETW inside uv__gethostnamew_nt60 */ +static GUID guid_host_name = SVCID_HOSTNAME; +static AFPROTOCOLS af_protocols[2] = { {AF_INET, IPPROTO_UDP}, + {AF_INET, IPPROTO_TCP} }; + /* * One-time initialization code for functionality defined in util.c. @@ -1663,6 +1673,125 @@ int uv_os_unsetenv(const char* name) { } +static int WSAAPI uv__gethostnamew_nt60(PWSTR name, int name_len) { + int result_len; + int error_code = NO_ERROR; + + /* WSALookupService stuff + * Avoid dynamic memory allocation if possible */ + CHAR local_buf[WSAQ_LOCAL_BUF_LEN]; + DWORD dwlen = WSAQ_LOCAL_BUF_LEN; + WSAQUERYSETW* pwsaq; + /* hostname returned from WSALookupService stage */ + WCHAR* result_name = NULL; + /* WSALookupService handle */ + HANDLE hlookup; + /* Fallback to heap allocation if stack buffer is too small */ + WSAQUERYSETW* heap_data = NULL; + + /* check input */ + if (name == NULL) { + error_code = WSAEFAULT; + goto cleanup; + } + + /* + * Stage 1: Check environment variable + * _CLUSTER_NETWORK_NAME_ len == ComputeName(NETBIOS) len. + * i.e 15 characters + null. + * It overrides the actual hostname, so application can + * work when network name and computer name are different + */ + result_len = GetEnvironmentVariableW(L"_CLUSTER_NETWORK_NAME_", + name, + name_len); + if (result_len != 0) { + if (result_len > name_len) { + error_code = WSAEFAULT; + } + goto cleanup; + } + + /* Stage 2: Do normal lookup through WSALookupServiceLookup */ + pwsaq = (WSAQUERYSETW*) local_buf; + memset(pwsaq, 0, sizeof(*pwsaq)); + pwsaq->dwSize = sizeof(*pwsaq); + pwsaq->lpszServiceInstanceName = NULL; + pwsaq->lpServiceClassId = &guid_host_name; + pwsaq->dwNameSpace = NS_ALL; + pwsaq->lpafpProtocols = &af_protocols[0]; + pwsaq->dwNumberOfProtocols = 2; + + error_code = WSALookupServiceBeginW(pwsaq, LUP_RETURN_NAME, &hlookup); + if (error_code == NO_ERROR) { + /* Try stack allocation first */ + error_code = WSALookupServiceNextW(hlookup, 0, &dwlen, pwsaq); + if (error_code == NO_ERROR) { + result_name = pwsaq->lpszServiceInstanceName; + } else { + error_code = WSAGetLastError(); + + if (error_code == WSAEFAULT) { + /* Should never happen */ + assert(sizeof(CHAR) * dwlen >= sizeof(WSAQUERYSETW)); + + /* Fallback to the heap allocation */ + heap_data = uv__malloc(sizeof(CHAR) * (size_t) dwlen); + if (heap_data != NULL) { + error_code = WSALookupServiceNextW(hlookup, 0, &dwlen, heap_data); + if (error_code == NO_ERROR) { + result_name = heap_data->lpszServiceInstanceName; + } else { + error_code = WSAGetLastError(); + } + } else { + error_code = WSA_NOT_ENOUGH_MEMORY; + } + } + } + + WSALookupServiceEnd(hlookup); + + if (error_code != NO_ERROR) { + WSASetLastError(error_code); + } + } + + if (result_name != NULL) { + size_t wlen = wcslen(result_name) + 1; + + if (wlen <= (size_t) name_len) { + wmemcpy(name, result_name, wlen); + } else { + error_code = WSAEFAULT; + } + goto cleanup; + } + + /* Stage 3: If WSALookupServiceLookup fails, fallback to GetComputerName */ + result_len = name_len; + /* Reset error code */ + error_code = NO_ERROR; + + if (GetComputerNameW(name, (PDWORD)&result_len) == FALSE) { + error_code = WSAENETDOWN; + if (result_len >= name_len) { + error_code = WSAEFAULT; + } + } + +cleanup: + uv__free(heap_data); + + if (error_code == NO_ERROR) { + return NO_ERROR; + } else { + WSASetLastError(error_code); + return SOCKET_ERROR; + } +} + + int uv_os_gethostname(char* buffer, size_t* size) { WCHAR buf[UV_MAXHOSTNAMESIZE]; size_t len;
closed
electron/electron
https://github.com/electron/electron
35,219
[Bug]: Win7 can't open electron app after upgrade to v19.x.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x.x ### What operating system are you using? Windows ### Operating System Version win7 ### What arch are you using? x64 ### Last Known Working Electron version 17.x.x ### Expected Behavior Can open and work. ### Actual Behavior Can not open program in win7 operate system. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35219
https://github.com/electron/electron/pull/35702
fa3cd1747556b66a3e714f99e988e47334187e44
7d3f22dd32365d5432583d936fa4c7f3d480ef45
2022-08-04T08:54:15Z
c++
2022-09-16T05:33:01Z
patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Tue, 16 Nov 2021 20:05:57 +0900 Subject: fix: suppress clang -Wdeprecated-declarations in libuv Should be upstreamed. diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 2d4cc0aaa02e61bf359e80eca27527efb49fd85e..aaa16052e2a9c7d1dca82763c41c0890371f1471 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -1950,10 +1950,17 @@ int uv_os_uname(uv_utsname_t* buffer) { #ifdef _MSC_VER #pragma warning(suppress : 4996) #endif + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + #endif if (GetVersionExW(&os_info) == 0) { r = uv_translate_sys_error(GetLastError()); goto error; } + #ifdef __clang__ + #pragma clang diagnostic pop + #endif } /* Populate the version field. */
closed
electron/electron
https://github.com/electron/electron
35,219
[Bug]: Win7 can't open electron app after upgrade to v19.x.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x.x ### What operating system are you using? Windows ### Operating System Version win7 ### What arch are you using? x64 ### Last Known Working Electron version 17.x.x ### Expected Behavior Can open and work. ### Actual Behavior Can not open program in win7 operate system. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35219
https://github.com/electron/electron/pull/35702
fa3cd1747556b66a3e714f99e988e47334187e44
7d3f22dd32365d5432583d936fa4c7f3d480ef45
2022-08-04T08:54:15Z
c++
2022-09-16T05:33:01Z
patches/node/fix_crash_caused_by_gethostnamew_on_windows_7.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Cheng Zhao <[email protected]> Date: Fri, 12 Nov 2021 17:25:37 +0900 Subject: fix: crash caused by GetHostNameW on Windows 7 Backported from https://github.com/libuv/libuv/pull/3285. diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 33e874ac442f88b58d2b68c8ec9764f6f664552e..2d4cc0aaa02e61bf359e80eca27527efb49fd85e 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -37,6 +37,7 @@ #include <psapi.h> #include <tlhelp32.h> #include <windows.h> +#include <svcguid.h> /* clang-format on */ #include <userenv.h> #include <math.h> @@ -56,6 +57,10 @@ /* The number of nanoseconds in one second. */ #define UV__NANOSEC 1000000000 +/* Local buffer size for WSAQUERYSETW data inside uv__gethostnamew_nt60 + sizeof(WSAQUERYSETW) + 512 = 632 bytes to match GetHostNameW behavior */ +#define WSAQ_LOCAL_BUF_LEN (sizeof(WSAQUERYSETW) + 512) + /* Max user name length, from iphlpapi.h */ #ifndef UNLEN # define UNLEN 256 @@ -72,6 +77,11 @@ static CRITICAL_SECTION process_title_lock; /* Frequency of the high-resolution clock. */ static uint64_t hrtime_frequency_ = 0; +/* Parameters for WSAQUERYSETW inside uv__gethostnamew_nt60 */ +static GUID guid_host_name = SVCID_HOSTNAME; +static AFPROTOCOLS af_protocols[2] = { {AF_INET, IPPROTO_UDP}, + {AF_INET, IPPROTO_TCP} }; + /* * One-time initialization code for functionality defined in util.c. @@ -1663,6 +1673,125 @@ int uv_os_unsetenv(const char* name) { } +static int WSAAPI uv__gethostnamew_nt60(PWSTR name, int name_len) { + int result_len; + int error_code = NO_ERROR; + + /* WSALookupService stuff + * Avoid dynamic memory allocation if possible */ + CHAR local_buf[WSAQ_LOCAL_BUF_LEN]; + DWORD dwlen = WSAQ_LOCAL_BUF_LEN; + WSAQUERYSETW* pwsaq; + /* hostname returned from WSALookupService stage */ + WCHAR* result_name = NULL; + /* WSALookupService handle */ + HANDLE hlookup; + /* Fallback to heap allocation if stack buffer is too small */ + WSAQUERYSETW* heap_data = NULL; + + /* check input */ + if (name == NULL) { + error_code = WSAEFAULT; + goto cleanup; + } + + /* + * Stage 1: Check environment variable + * _CLUSTER_NETWORK_NAME_ len == ComputeName(NETBIOS) len. + * i.e 15 characters + null. + * It overrides the actual hostname, so application can + * work when network name and computer name are different + */ + result_len = GetEnvironmentVariableW(L"_CLUSTER_NETWORK_NAME_", + name, + name_len); + if (result_len != 0) { + if (result_len > name_len) { + error_code = WSAEFAULT; + } + goto cleanup; + } + + /* Stage 2: Do normal lookup through WSALookupServiceLookup */ + pwsaq = (WSAQUERYSETW*) local_buf; + memset(pwsaq, 0, sizeof(*pwsaq)); + pwsaq->dwSize = sizeof(*pwsaq); + pwsaq->lpszServiceInstanceName = NULL; + pwsaq->lpServiceClassId = &guid_host_name; + pwsaq->dwNameSpace = NS_ALL; + pwsaq->lpafpProtocols = &af_protocols[0]; + pwsaq->dwNumberOfProtocols = 2; + + error_code = WSALookupServiceBeginW(pwsaq, LUP_RETURN_NAME, &hlookup); + if (error_code == NO_ERROR) { + /* Try stack allocation first */ + error_code = WSALookupServiceNextW(hlookup, 0, &dwlen, pwsaq); + if (error_code == NO_ERROR) { + result_name = pwsaq->lpszServiceInstanceName; + } else { + error_code = WSAGetLastError(); + + if (error_code == WSAEFAULT) { + /* Should never happen */ + assert(sizeof(CHAR) * dwlen >= sizeof(WSAQUERYSETW)); + + /* Fallback to the heap allocation */ + heap_data = uv__malloc(sizeof(CHAR) * (size_t) dwlen); + if (heap_data != NULL) { + error_code = WSALookupServiceNextW(hlookup, 0, &dwlen, heap_data); + if (error_code == NO_ERROR) { + result_name = heap_data->lpszServiceInstanceName; + } else { + error_code = WSAGetLastError(); + } + } else { + error_code = WSA_NOT_ENOUGH_MEMORY; + } + } + } + + WSALookupServiceEnd(hlookup); + + if (error_code != NO_ERROR) { + WSASetLastError(error_code); + } + } + + if (result_name != NULL) { + size_t wlen = wcslen(result_name) + 1; + + if (wlen <= (size_t) name_len) { + wmemcpy(name, result_name, wlen); + } else { + error_code = WSAEFAULT; + } + goto cleanup; + } + + /* Stage 3: If WSALookupServiceLookup fails, fallback to GetComputerName */ + result_len = name_len; + /* Reset error code */ + error_code = NO_ERROR; + + if (GetComputerNameW(name, (PDWORD)&result_len) == FALSE) { + error_code = WSAENETDOWN; + if (result_len >= name_len) { + error_code = WSAEFAULT; + } + } + +cleanup: + uv__free(heap_data); + + if (error_code == NO_ERROR) { + return NO_ERROR; + } else { + WSASetLastError(error_code); + return SOCKET_ERROR; + } +} + + int uv_os_gethostname(char* buffer, size_t* size) { WCHAR buf[UV_MAXHOSTNAMESIZE]; size_t len;
closed
electron/electron
https://github.com/electron/electron
35,219
[Bug]: Win7 can't open electron app after upgrade to v19.x.x
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.x.x ### What operating system are you using? Windows ### Operating System Version win7 ### What arch are you using? x64 ### Last Known Working Electron version 17.x.x ### Expected Behavior Can open and work. ### Actual Behavior Can not open program in win7 operate system. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/35219
https://github.com/electron/electron/pull/35702
fa3cd1747556b66a3e714f99e988e47334187e44
7d3f22dd32365d5432583d936fa4c7f3d480ef45
2022-08-04T08:54:15Z
c++
2022-09-16T05:33:01Z
patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Tue, 16 Nov 2021 20:05:57 +0900 Subject: fix: suppress clang -Wdeprecated-declarations in libuv Should be upstreamed. diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c index 2d4cc0aaa02e61bf359e80eca27527efb49fd85e..aaa16052e2a9c7d1dca82763c41c0890371f1471 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c @@ -1950,10 +1950,17 @@ int uv_os_uname(uv_utsname_t* buffer) { #ifdef _MSC_VER #pragma warning(suppress : 4996) #endif + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + #endif if (GetVersionExW(&os_info) == 0) { r = uv_translate_sys_error(GetLastError()); goto error; } + #ifdef __clang__ + #pragma clang diagnostic pop + #endif } /* Populate the version field. */
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` | null - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'content-bounds-updated' Returns: * `event` Event * `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs. By default, this will move the window. To prevent that behavior, call `event.preventDefault()`. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_browser_window.cc
// Copyright (c) 2013 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_browser_window.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/color_parser.h" #include "shell/browser/api/electron_api_web_contents_view.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/constructor.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "ui/gl/gpu_switching_manager.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/views/win_frame_view.h" #endif namespace electron::api { BrowserWindow::BrowserWindow(gin::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { // Use options.webPreferences in WebContents. v8::Isolate* isolate = args->isolate(); gin_helper::Dictionary web_preferences = gin::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); bool transparent = false; options.Get(options::kTransparent, &transparent); std::string vibrancy_type; #if BUILDFLAG(IS_MAC) options.Get(options::kVibrancyType, &vibrancy_type); #endif // Copy the backgroundColor to webContents. std::string color; if (options.Get(options::kBackgroundColor, &color)) { web_preferences.SetHidden(options::kBackgroundColor, color); } else if (!vibrancy_type.empty() || transparent) { // If the BrowserWindow is transparent or a vibrancy type has been set, // also propagate transparency to the WebContents unless a separate // backgroundColor has been set. web_preferences.SetHidden(options::kBackgroundColor, ToRGBAHex(SK_ColorTRANSPARENT)); } // Copy the show setting to webContents, but only if we don't want to paint // when initially hidden bool paint_when_initially_hidden = true; options.Get("paintWhenInitiallyHidden", &paint_when_initially_hidden); if (!paint_when_initially_hidden) { bool show = true; options.Get(options::kShow, &show); web_preferences.Set(options::kShow, show); } bool titleBarOverlay = false; options.Get(options::ktitleBarOverlay, &titleBarOverlay); if (titleBarOverlay) { std::string enabled_features = ""; if (web_preferences.Get(options::kEnableBlinkFeatures, &enabled_features)) { enabled_features += ","; } enabled_features += features::kWebAppWindowControlsOverlay.name; web_preferences.Set(options::kEnableBlinkFeatures, enabled_features); } // Copy the webContents option to webPreferences. v8::Local<v8::Value> value; if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } // Creates the WebContentsView. gin::Handle<WebContentsView> web_contents_view = WebContentsView::Create(isolate, web_preferences); DCHECK(web_contents_view.get()); // Save a reference of the WebContents. gin::Handle<WebContents> web_contents = web_contents_view->GetWebContents(isolate); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents->GetWeakPtr(); api_web_contents_->AddObserver(this); Observe(api_web_contents_->web_contents()); // Associate with BrowserWindow. web_contents->SetOwnerWindow(window()); auto* host = web_contents->web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); #if BUILDFLAG(IS_MAC) OverrideNSWindowContentView( web_contents->inspectable_web_contents()->GetView()); #endif // Init window after everything has been setup. window()->InitFromOptions(options); } BrowserWindow::~BrowserWindow() { if (api_web_contents_) { // Cleanup the observers if user destroyed this instance directly instead of // gracefully closing content::WebContents. auto* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); } } void BrowserWindow::OnInputEvent(const blink::WebInputEvent& event) { switch (event.GetType()) { case blink::WebInputEvent::Type::kGestureScrollBegin: case blink::WebInputEvent::Type::kGestureScrollUpdate: case blink::WebInputEvent::Type::kGestureScrollEnd: Emit("scroll-touch-edge"); break; default: break; } } void BrowserWindow::RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) { if (old_host) old_host->GetWidget()->RemoveInputEventObserver(this); if (new_host) new_host->GetWidget()->AddInputEventObserver(this); } void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); // Cancel unresponsive event when window close is cancelled. window_unresponsive_closure_.Cancel(); } void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) { // Schedule the unresponsive shortly later, since we may receive the // responsive event soon. This could happen after the whole application had // blocked for a while. // Also notice that when closing this event would be ignored because we have // explicitly started a close timeout counter. This is on purpose because we // don't want the unresponsive event to be sent too early when user is closing // the window. ScheduleUnresponsiveEvent(50); } void BrowserWindow::WebContentsDestroyed() { api_web_contents_ = nullptr; CloseImmediately(); } void BrowserWindow::OnCloseContents() { BaseWindow::ResetBrowserViews(); api_web_contents_->Destroy(); } void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { window_unresponsive_closure_.Cancel(); Emit("responsive"); } void BrowserWindow::OnDraggableRegionsUpdated( const std::vector<mojom::DraggableRegionPtr>& regions) { UpdateDraggableRegions(regions); } void BrowserWindow::OnSetContentBounds(const gfx::Rect& rect) { // window.resizeTo(...) // window.moveTo(...) window()->SetBounds(rect, false); } void BrowserWindow::OnActivateContents() { // Hide the auto-hide menu when webContents is focused. #if !BUILDFLAG(IS_MAC) if (IsMenuBarAutoHide() && IsMenuBarVisible()) window()->SetMenuBarVisibility(false); #endif } void BrowserWindow::OnPageTitleUpdated(const std::u16string& title, bool explicit_set) { // Change window title to page title. auto self = GetWeakPtr(); if (!Emit("page-title-updated", title, explicit_set)) { // |this| might be deleted, or marked as destroyed by close(). if (self && !IsDestroyed()) SetTitle(base::UTF16ToUTF8(title)); } } void BrowserWindow::RequestPreferredWidth(int* width) { *width = web_contents()->GetPreferredSize().width(); } void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) { // When user tries to close the window by clicking the close button, we do // not close the window immediately, instead we try to close the web page // first, and when the web page is closed the window will also be closed. *prevent_default = true; // Assume the window is not responding if it doesn't cancel the close and is // not closed in 5s, in this way we can quickly show the unresponsive // dialog when the window is busy executing some script without waiting for // the unresponsive timeout. if (window_unresponsive_closure_.IsCancelled()) ScheduleUnresponsiveEvent(5000); // Already closed by renderer. if (!web_contents() || !api_web_contents_) return; // Required to make beforeunload handler work. api_web_contents_->NotifyUserActivation(); // Trigger beforeunload events for associated BrowserViews. for (NativeBrowserView* view : window_->browser_views()) { auto* vwc = view->web_contents(); auto* api_web_contents = api::WebContents::From(vwc); // Required to make beforeunload handler work. if (api_web_contents) api_web_contents->NotifyUserActivation(); if (vwc) { if (vwc->NeedToFireBeforeUnloadOrUnloadEvents()) { vwc->DispatchBeforeUnload(false /* auto_cancel */); } } } if (web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } void BrowserWindow::OnWindowBlur() { if (api_web_contents_) web_contents()->StoreFocus(); BaseWindow::OnWindowBlur(); } void BrowserWindow::OnWindowFocus() { // focus/blur events might be emitted while closing window. if (api_web_contents_) { web_contents()->RestoreFocus(); #if !BUILDFLAG(IS_MAC) if (!api_web_contents_->IsDevToolsOpened()) web_contents()->Focus(); #endif } BaseWindow::OnWindowFocus(); } void BrowserWindow::OnWindowIsKeyChanged(bool is_key) { #if BUILDFLAG(IS_MAC) auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetActive(is_key); window()->SetActive(is_key); #endif } void BrowserWindow::OnWindowResize() { #if BUILDFLAG(IS_MAC) if (!draggable_regions_.empty()) { UpdateDraggableRegions(draggable_regions_); } else { for (NativeBrowserView* view : window_->browser_views()) { view->UpdateDraggableRegions(view->GetDraggableRegions()); } } #endif BaseWindow::OnWindowResize(); } void BrowserWindow::OnWindowLeaveFullScreen() { #if BUILDFLAG(IS_MAC) if (web_contents()->IsFullscreen()) web_contents()->ExitFullscreen(true); #endif BaseWindow::OnWindowLeaveFullScreen(); } void BrowserWindow::UpdateWindowControlsOverlay( const gfx::Rect& bounding_rect) { web_contents()->UpdateWindowControlsOverlay(bounding_rect); } void BrowserWindow::CloseImmediately() { // Close all child windows before closing current window. v8::HandleScope handle_scope(isolate()); for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) { gin::Handle<BrowserWindow> child; if (gin::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty()) child->window()->CloseImmediately(); } BaseWindow::CloseImmediately(); // Do not sent "unresponsive" event after window is closed. window_unresponsive_closure_.Cancel(); } void BrowserWindow::Focus() { if (api_web_contents_->IsOffScreen()) FocusOnWebView(); else BaseWindow::Focus(); } void BrowserWindow::Blur() { if (api_web_contents_->IsOffScreen()) BlurWebView(); else BaseWindow::Blur(); } void BrowserWindow::SetBackgroundColor(const std::string& color_name) { BaseWindow::SetBackgroundColor(color_name); SkColor color = ParseCSSColor(color_name); web_contents()->SetPageBaseBackgroundColor(color); auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Also update the web preferences object otherwise the view will be reset on // the next load URL call if (api_web_contents_) { auto* web_preferences = WebContentsPreferences::From(api_web_contents_->web_contents()); if (web_preferences) { web_preferences->SetBackgroundColor(ParseCSSColor(color_name)); } } } void BrowserWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { BaseWindow::ResetBrowserViews(); if (browser_view) BaseWindow::AddBrowserView(*browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { BaseWindow::AddBrowserView(browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { BaseWindow::RemoveBrowserView(browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow::SetTopBrowserView(browser_view, args); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::ResetBrowserViews() { BaseWindow::ResetBrowserViews(); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::OnDevToolsResized() { UpdateDraggableRegions(draggable_regions_); } void BrowserWindow::FocusOnWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Focus(); } void BrowserWindow::BlurWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Blur(); } bool BrowserWindow::IsWebViewFocused() { auto* host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView(); return host_view && host_view->HasFocus(); } v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) return v8::Null(isolate); return v8::Local<v8::Value>::New(isolate, web_contents_); } #if BUILDFLAG(IS_WIN) void BrowserWindow::SetTitleBarOverlay(const gin_helper::Dictionary& options, gin_helper::Arguments* args) { // Ensure WCO is already enabled on this window if (!window_->titlebar_overlay_enabled()) { args->ThrowError("Titlebar overlay is not enabled"); return; } auto* window = static_cast<NativeWindowViews*>(window_.get()); bool updated = false; // Check and update the button color std::string btn_color; if (options.Get(options::kOverlayButtonColor, &btn_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(btn_color, &color)) { args->ThrowError("Could not parse color as CSS color"); return; } // Update the view window->set_overlay_button_color(color); updated = true; } // Check and update the symbol color std::string symbol_color; if (options.Get(options::kOverlaySymbolColor, &symbol_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(symbol_color, &color)) { args->ThrowError("Could not parse symbol color as CSS color"); return; } // Update the view window->set_overlay_symbol_color(color); updated = true; } // Check and update the height int height = 0; if (options.Get(options::kOverlayHeight, &height)) { window->set_titlebar_overlay_height(height); updated = true; } // If anything was updated, invalidate the layout and schedule a paint of the // window's frame view if (updated) { auto* frame_view = static_cast<WinFrameView*>( window->widget()->non_client_view()->frame_view()); frame_view->InvalidateCaptionButtons(); } } #endif void BrowserWindow::ScheduleUnresponsiveEvent(int ms) { if (!window_unresponsive_closure_.IsCancelled()) return; window_unresponsive_closure_.Reset(base::BindRepeating( &BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr())); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, window_unresponsive_closure_.callback(), base::Milliseconds(ms)); } void BrowserWindow::NotifyWindowUnresponsive() { window_unresponsive_closure_.Cancel(); if (!window_->IsClosed() && window_->IsEnabled()) { Emit("unresponsive"); } } void BrowserWindow::OnWindowShow() { web_contents()->WasShown(); BaseWindow::OnWindowShow(); } void BrowserWindow::OnWindowHide() { web_contents()->WasOccluded(); BaseWindow::OnWindowHide(); } // static gin_helper::WrappableBase* BrowserWindow::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserWindow before app is ready"); return nullptr; } if (args->Length() > 1) { args->ThrowError(); return nullptr; } gin_helper::Dictionary options; if (!(args->Length() == 1 && args->GetNext(&options))) { options = gin::Dictionary::CreateEmpty(args->isolate()); } return new BrowserWindow(args, options); } // static void BrowserWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BrowserWindow")); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("focusOnWebView", &BrowserWindow::FocusOnWebView) .SetMethod("blurWebView", &BrowserWindow::BlurWebView) .SetMethod("isWebViewFocused", &BrowserWindow::IsWebViewFocused) #if BUILDFLAG(IS_WIN) .SetMethod("setTitleBarOverlay", &BrowserWindow::SetTitleBarOverlay) #endif .SetProperty("webContents", &BrowserWindow::GetWebContents); } // static v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate, NativeWindow* native_window) { auto* existing = TrackableObject::FromWrappedClass(isolate, native_window); if (existing) return existing->GetWrapper(); else return v8::Null(isolate); } } // namespace electron::api namespace { using electron::api::BrowserWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("BrowserWindow", gin_helper::CreateConstructor<BrowserWindow>( isolate, base::BindRepeating(&BrowserWindow::New))); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_web_contents.cc
// 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/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/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.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/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.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/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/result_codes.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/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.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/file_select_helper.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_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.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 BUILDFLAG(IS_WIN) #include "shell/browser/native_window_views.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif // BUILDFLAG(ENABLE_PRINTING) #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::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 BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(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 BUILDFLAG(IS_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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_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 if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), 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 !BUILDFLAG(IS_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 BUILDFLAG(IS_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().DeprecatedGetOriginAsURL(); 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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = 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(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // 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::kOffscreenDocument: 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; 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()); InitWithWebContents(std::move(owned_web_contents), 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 BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(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); // 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::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&WebContents::DeleteThisIfAlive, 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; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { if (!Emit("content-bounds-updated", rect)) for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(requesting_frame, callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } #if BUILDFLAG(IS_WIN) auto* win = static_cast<NativeWindowViews*>(owner_window()); // Force a detached state when WCO is enabled to match Chrome // behavior and prevent occlusion of DevTools. if (win && win->IsWindowControlsOverlayEnabled()) state = "detach"; #endif DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDeviceNameToUse(base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings); void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void 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); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated'); const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated'); const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` | null - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'content-bounds-updated' Returns: * `event` Event * `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs. By default, this will move the window. To prevent that behavior, call `event.preventDefault()`. #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. See also [`webContents.ipc`](#contentsipc-readonly), which provides an [`IpcMain`](ipc-main.md)-like interface for responding to IPC messages specifically from this WebContents. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'. Sets the [cascade origin](https://www.w3.org/TR/css3-cascade/#cascade-origin) of the inserted stylesheet. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `landscape` boolean (optional) - Paper orientation.`true` for landscape, `false` for portrait. Defaults to false. * `displayHeaderFooter` boolean (optional) - Whether to display header and footer. Defaults to false. * `printBackground` boolean (optional) - Whether to print background graphics. Defaults to false. * `scale` number(optional) - Scale of the webpage rendering. Defaults to 1. * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `Legal`, `Letter`, `Tabloid`, `Ledger`, or an Object containing `height` and `width` in inches. Defaults to `Letter`. * `margins` Object (optional) * `top` number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches). * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints the window's web page as PDF. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow() win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` See [Page.printToPdf](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) for more information. #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. On Windows, if Windows Control Overlay is enabled, Devtools will be opened with `mode: 'detach'`. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The absolute file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.ipc` _Readonly_ An [`IpcMain`](ipc-main.md) scoped to just IPC messages sent from this WebContents. IPC messages sent with `ipcRenderer.send`, `ipcRenderer.sendSync` or `ipcRenderer.postMessage` will be delivered in the following order: 1. `contents.on('ipc-message')` 2. `contents.mainFrame.on(channel)` 3. `contents.ipc.on(channel)` 4. `ipcMain.on(channel)` Handlers registered with `invoke` will be checked in the following order. The first one that is defined will be called, the rest will be ignored. 1. `contents.mainFrame.handle(channel)` 2. `contents.handle(channel)` 3. `ipcMain.handle(channel)` A handler or event listener registered on the WebContents will receive IPC messages sent from any frame, including child frames. In most cases, only the main frame can send IPC messages. However, if the `nodeIntegrationInSubFrames` option is enabled, it is possible for child frames to send IPC messages also. In that case, handlers should check the `senderFrame` property of the IPC event to ensure that the message is coming from the expected frame. Alternatively, register handlers on the appropriate frame directly using the [`WebFrameMain.ipc`](web-frame-main.md#frameipc-readonly) interface. #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_browser_window.cc
// Copyright (c) 2013 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_browser_window.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck #include "content/browser/web_contents/web_contents_impl.h" // nogncheck #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/color_parser.h" #include "shell/browser/api/electron_api_web_contents_view.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/constructor.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "ui/gl/gpu_switching_manager.h" #if defined(TOOLKIT_VIEWS) #include "shell/browser/native_window_views.h" #endif #if BUILDFLAG(IS_WIN) #include "shell/browser/ui/views/win_frame_view.h" #endif namespace electron::api { BrowserWindow::BrowserWindow(gin::Arguments* args, const gin_helper::Dictionary& options) : BaseWindow(args->isolate(), options) { // Use options.webPreferences in WebContents. v8::Isolate* isolate = args->isolate(); gin_helper::Dictionary web_preferences = gin::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); bool transparent = false; options.Get(options::kTransparent, &transparent); std::string vibrancy_type; #if BUILDFLAG(IS_MAC) options.Get(options::kVibrancyType, &vibrancy_type); #endif // Copy the backgroundColor to webContents. std::string color; if (options.Get(options::kBackgroundColor, &color)) { web_preferences.SetHidden(options::kBackgroundColor, color); } else if (!vibrancy_type.empty() || transparent) { // If the BrowserWindow is transparent or a vibrancy type has been set, // also propagate transparency to the WebContents unless a separate // backgroundColor has been set. web_preferences.SetHidden(options::kBackgroundColor, ToRGBAHex(SK_ColorTRANSPARENT)); } // Copy the show setting to webContents, but only if we don't want to paint // when initially hidden bool paint_when_initially_hidden = true; options.Get("paintWhenInitiallyHidden", &paint_when_initially_hidden); if (!paint_when_initially_hidden) { bool show = true; options.Get(options::kShow, &show); web_preferences.Set(options::kShow, show); } bool titleBarOverlay = false; options.Get(options::ktitleBarOverlay, &titleBarOverlay); if (titleBarOverlay) { std::string enabled_features = ""; if (web_preferences.Get(options::kEnableBlinkFeatures, &enabled_features)) { enabled_features += ","; } enabled_features += features::kWebAppWindowControlsOverlay.name; web_preferences.Set(options::kEnableBlinkFeatures, enabled_features); } // Copy the webContents option to webPreferences. v8::Local<v8::Value> value; if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } // Creates the WebContentsView. gin::Handle<WebContentsView> web_contents_view = WebContentsView::Create(isolate, web_preferences); DCHECK(web_contents_view.get()); // Save a reference of the WebContents. gin::Handle<WebContents> web_contents = web_contents_view->GetWebContents(isolate); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents->GetWeakPtr(); api_web_contents_->AddObserver(this); Observe(api_web_contents_->web_contents()); // Associate with BrowserWindow. web_contents->SetOwnerWindow(window()); auto* host = web_contents->web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); #if BUILDFLAG(IS_MAC) OverrideNSWindowContentView( web_contents->inspectable_web_contents()->GetView()); #endif // Init window after everything has been setup. window()->InitFromOptions(options); } BrowserWindow::~BrowserWindow() { if (api_web_contents_) { // Cleanup the observers if user destroyed this instance directly instead of // gracefully closing content::WebContents. auto* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); } } void BrowserWindow::OnInputEvent(const blink::WebInputEvent& event) { switch (event.GetType()) { case blink::WebInputEvent::Type::kGestureScrollBegin: case blink::WebInputEvent::Type::kGestureScrollUpdate: case blink::WebInputEvent::Type::kGestureScrollEnd: Emit("scroll-touch-edge"); break; default: break; } } void BrowserWindow::RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) { if (old_host) old_host->GetWidget()->RemoveInputEventObserver(this); if (new_host) new_host->GetWidget()->AddInputEventObserver(this); } void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); // Cancel unresponsive event when window close is cancelled. window_unresponsive_closure_.Cancel(); } void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) { // Schedule the unresponsive shortly later, since we may receive the // responsive event soon. This could happen after the whole application had // blocked for a while. // Also notice that when closing this event would be ignored because we have // explicitly started a close timeout counter. This is on purpose because we // don't want the unresponsive event to be sent too early when user is closing // the window. ScheduleUnresponsiveEvent(50); } void BrowserWindow::WebContentsDestroyed() { api_web_contents_ = nullptr; CloseImmediately(); } void BrowserWindow::OnCloseContents() { BaseWindow::ResetBrowserViews(); api_web_contents_->Destroy(); } void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { window_unresponsive_closure_.Cancel(); Emit("responsive"); } void BrowserWindow::OnDraggableRegionsUpdated( const std::vector<mojom::DraggableRegionPtr>& regions) { UpdateDraggableRegions(regions); } void BrowserWindow::OnSetContentBounds(const gfx::Rect& rect) { // window.resizeTo(...) // window.moveTo(...) window()->SetBounds(rect, false); } void BrowserWindow::OnActivateContents() { // Hide the auto-hide menu when webContents is focused. #if !BUILDFLAG(IS_MAC) if (IsMenuBarAutoHide() && IsMenuBarVisible()) window()->SetMenuBarVisibility(false); #endif } void BrowserWindow::OnPageTitleUpdated(const std::u16string& title, bool explicit_set) { // Change window title to page title. auto self = GetWeakPtr(); if (!Emit("page-title-updated", title, explicit_set)) { // |this| might be deleted, or marked as destroyed by close(). if (self && !IsDestroyed()) SetTitle(base::UTF16ToUTF8(title)); } } void BrowserWindow::RequestPreferredWidth(int* width) { *width = web_contents()->GetPreferredSize().width(); } void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) { // When user tries to close the window by clicking the close button, we do // not close the window immediately, instead we try to close the web page // first, and when the web page is closed the window will also be closed. *prevent_default = true; // Assume the window is not responding if it doesn't cancel the close and is // not closed in 5s, in this way we can quickly show the unresponsive // dialog when the window is busy executing some script without waiting for // the unresponsive timeout. if (window_unresponsive_closure_.IsCancelled()) ScheduleUnresponsiveEvent(5000); // Already closed by renderer. if (!web_contents() || !api_web_contents_) return; // Required to make beforeunload handler work. api_web_contents_->NotifyUserActivation(); // Trigger beforeunload events for associated BrowserViews. for (NativeBrowserView* view : window_->browser_views()) { auto* vwc = view->web_contents(); auto* api_web_contents = api::WebContents::From(vwc); // Required to make beforeunload handler work. if (api_web_contents) api_web_contents->NotifyUserActivation(); if (vwc) { if (vwc->NeedToFireBeforeUnloadOrUnloadEvents()) { vwc->DispatchBeforeUnload(false /* auto_cancel */); } } } if (web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } void BrowserWindow::OnWindowBlur() { if (api_web_contents_) web_contents()->StoreFocus(); BaseWindow::OnWindowBlur(); } void BrowserWindow::OnWindowFocus() { // focus/blur events might be emitted while closing window. if (api_web_contents_) { web_contents()->RestoreFocus(); #if !BUILDFLAG(IS_MAC) if (!api_web_contents_->IsDevToolsOpened()) web_contents()->Focus(); #endif } BaseWindow::OnWindowFocus(); } void BrowserWindow::OnWindowIsKeyChanged(bool is_key) { #if BUILDFLAG(IS_MAC) auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetActive(is_key); window()->SetActive(is_key); #endif } void BrowserWindow::OnWindowResize() { #if BUILDFLAG(IS_MAC) if (!draggable_regions_.empty()) { UpdateDraggableRegions(draggable_regions_); } else { for (NativeBrowserView* view : window_->browser_views()) { view->UpdateDraggableRegions(view->GetDraggableRegions()); } } #endif BaseWindow::OnWindowResize(); } void BrowserWindow::OnWindowLeaveFullScreen() { #if BUILDFLAG(IS_MAC) if (web_contents()->IsFullscreen()) web_contents()->ExitFullscreen(true); #endif BaseWindow::OnWindowLeaveFullScreen(); } void BrowserWindow::UpdateWindowControlsOverlay( const gfx::Rect& bounding_rect) { web_contents()->UpdateWindowControlsOverlay(bounding_rect); } void BrowserWindow::CloseImmediately() { // Close all child windows before closing current window. v8::HandleScope handle_scope(isolate()); for (v8::Local<v8::Value> value : child_windows_.Values(isolate())) { gin::Handle<BrowserWindow> child; if (gin::ConvertFromV8(isolate(), value, &child) && !child.IsEmpty()) child->window()->CloseImmediately(); } BaseWindow::CloseImmediately(); // Do not sent "unresponsive" event after window is closed. window_unresponsive_closure_.Cancel(); } void BrowserWindow::Focus() { if (api_web_contents_->IsOffScreen()) FocusOnWebView(); else BaseWindow::Focus(); } void BrowserWindow::Blur() { if (api_web_contents_->IsOffScreen()) BlurWebView(); else BaseWindow::Blur(); } void BrowserWindow::SetBackgroundColor(const std::string& color_name) { BaseWindow::SetBackgroundColor(color_name); SkColor color = ParseCSSColor(color_name); web_contents()->SetPageBaseBackgroundColor(color); auto* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Also update the web preferences object otherwise the view will be reset on // the next load URL call if (api_web_contents_) { auto* web_preferences = WebContentsPreferences::From(api_web_contents_->web_contents()); if (web_preferences) { web_preferences->SetBackgroundColor(ParseCSSColor(color_name)); } } } void BrowserWindow::SetBrowserView( absl::optional<gin::Handle<BrowserView>> browser_view) { BaseWindow::ResetBrowserViews(); if (browser_view) BaseWindow::AddBrowserView(*browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::AddBrowserView(gin::Handle<BrowserView> browser_view) { BaseWindow::AddBrowserView(browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::RemoveBrowserView(gin::Handle<BrowserView> browser_view) { BaseWindow::RemoveBrowserView(browser_view); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::SetTopBrowserView(gin::Handle<BrowserView> browser_view, gin_helper::Arguments* args) { BaseWindow::SetTopBrowserView(browser_view, args); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::ResetBrowserViews() { BaseWindow::ResetBrowserViews(); #if BUILDFLAG(IS_MAC) UpdateDraggableRegions(draggable_regions_); #endif } void BrowserWindow::OnDevToolsResized() { UpdateDraggableRegions(draggable_regions_); } void BrowserWindow::FocusOnWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Focus(); } void BrowserWindow::BlurWebView() { web_contents()->GetRenderViewHost()->GetWidget()->Blur(); } bool BrowserWindow::IsWebViewFocused() { auto* host_view = web_contents()->GetRenderViewHost()->GetWidget()->GetView(); return host_view && host_view->HasFocus(); } v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) return v8::Null(isolate); return v8::Local<v8::Value>::New(isolate, web_contents_); } #if BUILDFLAG(IS_WIN) void BrowserWindow::SetTitleBarOverlay(const gin_helper::Dictionary& options, gin_helper::Arguments* args) { // Ensure WCO is already enabled on this window if (!window_->titlebar_overlay_enabled()) { args->ThrowError("Titlebar overlay is not enabled"); return; } auto* window = static_cast<NativeWindowViews*>(window_.get()); bool updated = false; // Check and update the button color std::string btn_color; if (options.Get(options::kOverlayButtonColor, &btn_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(btn_color, &color)) { args->ThrowError("Could not parse color as CSS color"); return; } // Update the view window->set_overlay_button_color(color); updated = true; } // Check and update the symbol color std::string symbol_color; if (options.Get(options::kOverlaySymbolColor, &symbol_color)) { // Parse the string as a CSS color SkColor color; if (!content::ParseCssColorString(symbol_color, &color)) { args->ThrowError("Could not parse symbol color as CSS color"); return; } // Update the view window->set_overlay_symbol_color(color); updated = true; } // Check and update the height int height = 0; if (options.Get(options::kOverlayHeight, &height)) { window->set_titlebar_overlay_height(height); updated = true; } // If anything was updated, invalidate the layout and schedule a paint of the // window's frame view if (updated) { auto* frame_view = static_cast<WinFrameView*>( window->widget()->non_client_view()->frame_view()); frame_view->InvalidateCaptionButtons(); } } #endif void BrowserWindow::ScheduleUnresponsiveEvent(int ms) { if (!window_unresponsive_closure_.IsCancelled()) return; window_unresponsive_closure_.Reset(base::BindRepeating( &BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr())); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, window_unresponsive_closure_.callback(), base::Milliseconds(ms)); } void BrowserWindow::NotifyWindowUnresponsive() { window_unresponsive_closure_.Cancel(); if (!window_->IsClosed() && window_->IsEnabled()) { Emit("unresponsive"); } } void BrowserWindow::OnWindowShow() { web_contents()->WasShown(); BaseWindow::OnWindowShow(); } void BrowserWindow::OnWindowHide() { web_contents()->WasOccluded(); BaseWindow::OnWindowHide(); } // static gin_helper::WrappableBase* BrowserWindow::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserWindow before app is ready"); return nullptr; } if (args->Length() > 1) { args->ThrowError(); return nullptr; } gin_helper::Dictionary options; if (!(args->Length() == 1 && args->GetNext(&options))) { options = gin::Dictionary::CreateEmpty(args->isolate()); } return new BrowserWindow(args, options); } // static void BrowserWindow::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(gin::StringToV8(isolate, "BrowserWindow")); gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) .SetMethod("focusOnWebView", &BrowserWindow::FocusOnWebView) .SetMethod("blurWebView", &BrowserWindow::BlurWebView) .SetMethod("isWebViewFocused", &BrowserWindow::IsWebViewFocused) #if BUILDFLAG(IS_WIN) .SetMethod("setTitleBarOverlay", &BrowserWindow::SetTitleBarOverlay) #endif .SetProperty("webContents", &BrowserWindow::GetWebContents); } // static v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate, NativeWindow* native_window) { auto* existing = TrackableObject::FromWrappedClass(isolate, native_window); if (existing) return existing->GetWrapper(); else return v8::Null(isolate); } } // namespace electron::api namespace { using electron::api::BrowserWindow; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("BrowserWindow", gin_helper::CreateConstructor<BrowserWindow>( isolate, base::BindRepeating(&BrowserWindow::New))); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_web_contents.cc
// 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/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/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/embedder_support/user_agent_utils.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/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.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/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/result_codes.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/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.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/file_select_helper.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_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.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 BUILDFLAG(IS_WIN) #include "shell/browser/native_window_views.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/linux/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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 "chrome/browser/printing/print_view_manager_base.h" #include "components/printing/browser/print_manager_utils.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" // nogncheck #include "printing/page_range.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif // BUILDFLAG(ENABLE_PRINTING) #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::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 BUILDFLAG(IS_MAC) absl::optional<base::TimeDelta> system_value( ui::TextInsertionCaretBlinkPeriodFromDefaults()); if (system_value) return *system_value; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = ui::LinuxUi::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(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 BUILDFLAG(IS_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; #else scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name)); #endif } // This function returns a validated device name. // If the user passed one to webContents.print(), we check that it's valid and // return it or fail if the network doesn't recognize it. If the user didn't // pass a device name, we first try to return the system default printer. If one // isn't set, then pull all the printers and use the first one or fail if none // exist. std::pair<std::string, std::u16string> GetDeviceNameToUse( const std::u16string& device_name) { #if BUILDFLAG(IS_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 if (!device_name.empty()) { if (!IsDeviceNameValid(device_name)) return std::make_pair("Invalid deviceName provided", std::u16string()); return std::make_pair(std::string(), device_name); } scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (printers.empty()) return std::make_pair("No printers available on the network", std::u16string()); printer_name = printers.front().printer_name; } return std::make_pair(std::string(), 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 !BUILDFLAG(IS_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 BUILDFLAG(IS_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().DeprecatedGetOriginAsURL(); 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); } base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) { base::Value::Dict value; value.Set("type", file_system.type); value.Set("fileSystemName", file_system.file_system_name); value.Set("rootURL", file_system.root_url); value.Set("fileSystemPath", file_system.file_system_path); return 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::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = 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(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // 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::kOffscreenDocument: 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), 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()) { // webPreferences does not have a transparent option, so if the window needs // to be transparent, that will be set at electron_api_browser_window.cc#L57 // and we then need to pull it back out and check it here. std::string background_color; options.GetHidden(options::kBackgroundColor, &background_color); bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT; 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()); InitWithWebContents(std::move(owned_web_contents), 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 BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_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()); SetUserAgent(GetBrowserContext()->GetUserAgent()); 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(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintViewManagerElectron::CreateForWebContents(web_contents.get()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(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); // 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::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&WebContents::DeleteThisIfAlive, 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; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, window_features.bounds.x(), window_features.bounds.y(), window_features.bounds.width(), window_features.bounds.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { if (!Emit("content-bounds-updated", rect)) for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(requesting_frame, callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::HTML); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { absl::optional<SkColor> maybe_color = web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(maybe_color); bool guest = IsGuest() || type_ == Type::kBrowserView; SkColor color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); SetBackgroundColor(rwhv, color); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->MaybeSetupMojoConnection(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetPrimaryMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronApiIPC::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "setInspectedTabId", base::Value(ID())); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetPrimaryMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents() ->GetPrimaryMainFrame() ->GetProcess() ->GetProcess() .Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) SetUserAgent(user_agent); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discard non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetPrimaryMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { blink::UserAgentOverride ua_override; ua_override.ua_string_override = user_agent; if (!user_agent.empty()) ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata(); web_contents()->SetUserAgentOverride(ua_override, false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } #if BUILDFLAG(IS_WIN) auto* win = static_cast<NativeWindowViews*>(owner_window()); // Force a detached state when WCO is enabled to match Chrome // behavior and prevent occlusion of DevTools. if (win && win->IsWindowControlsOverlayEnabled()) state = "detach"; #endif DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDeviceNameToUse( base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. print_settings.Set(printing::kSettingDeviceName, info.second); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetPrimaryMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value::Dict settings; if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.Set(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value::Dict custom_margins; int top = 0; margins.Get("top", &top); custom_margins.Set(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.Set(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.Set(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.Set(printing::kSettingMarginRight, right); settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.Set( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.Set(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.Set(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.Set(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.Set(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.Set(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.Set(printing::kSettingHeaderFooterEnabled, true); settings.Set(printing::kSettingHeaderFooterTitle, header); settings.Set(printing::kSettingHeaderFooterURL, footer); } else { settings.Set(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.Set(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.Set(printing::kSettingShouldPrintSelectionOnly, false); settings.Set(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value::List page_range_list; for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value::Dict range_dict; // Chromium uses 1-based page ranges, so increment each by 1. range_dict.Set(printing::kSettingPageRangeFrom, from + 1); range_dict.Set(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range_dict)); } else { continue; } } if (!page_range_list.empty()) settings.Set(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.Set(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.Set(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.Set(printing::kSettingDpiVertical, vertical); } else { settings.Set(printing::kSettingDpiHorizontal, dpi); settings.Set(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name), base::BindOnce(&WebContents::OnGetDeviceNameToUse, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), silent)); } // Partially duplicated and modified from // headless/lib/browser/protocol/page_handler.cc;l=41 v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // This allows us to track headless printing calls. auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID); auto landscape = settings.GetDict().FindBool("landscape"); auto display_header_footer = settings.GetDict().FindBool("displayHeaderFooter"); auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds"); auto scale = settings.GetDict().FindDouble("scale"); auto paper_width = settings.GetDict().FindInt("paperWidth"); auto paper_height = settings.GetDict().FindInt("paperHeight"); auto margin_top = settings.GetDict().FindIntByDottedPath("margins.top"); auto margin_bottom = settings.GetDict().FindIntByDottedPath("margins.bottom"); auto margin_left = settings.GetDict().FindIntByDottedPath("margins.left"); auto margin_right = settings.GetDict().FindIntByDottedPath("margins.right"); auto page_ranges = *settings.GetDict().FindString("pageRanges"); auto header_template = *settings.GetDict().FindString("headerTemplate"); auto footer_template = *settings.GetDict().FindString("footerTemplate"); auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize"); absl::variant<printing::mojom::PrintPagesParamsPtr, std::string> print_pages_params = print_to_pdf::GetPrintPagesParams( web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(), landscape, display_header_footer, print_background, scale, paper_width, paper_height, margin_top, margin_bottom, margin_left, margin_right, absl::make_optional(header_template), absl::make_optional(footer_template), prefer_css_page_size); if (absl::holds_alternative<std::string>(print_pages_params)) { auto error = absl::get<std::string>(print_pages_params); promise.RejectWithErrorMessage("Invalid print parameters: " + error); return handle; } auto* manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!manager) { promise.RejectWithErrorMessage("Failed to find print manager"); return handle; } auto params = std::move( absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params)); params->params->document_cookie = unique_id.value_or(0); manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges, std::move(params), base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(), std::move(promise))); return handle; } void WebContents::OnPDFCreated( gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != PrintViewManagerElectron::PrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + PrintViewManagerElectron::PrintResultToString(print_result)); return; } v8::Isolate* isolate = promise.isolate(); gin_helper::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope( v8::Local<v8::Context>::New(isolate, promise.GetContext())); v8::Local<v8::Value> buffer = node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()), data->size()) .ToLocalChecked(); promise.Resolve(buffer); } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetPrimaryMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetPrimaryMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents() ->IncrementCapturerCount(size, stay_hidden, stay_awake) .Release(); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetPrimaryMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { if (!owner_window()) return html_fullscreen_; bool in_transition = owner_window()->fullscreen_transition_state() != NativeWindow::FullScreenTransitionState::NONE; bool is_html_transition = owner_window()->fullscreen_transition_type() == NativeWindow::FullScreenTransitionType::HTML; return html_fullscreen_ || (in_transition && is_html_transition); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance() ->EnterVideoPictureInPicture(web_contents); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "canceledSaveURL", base::Value(url)); return; } } saved_files_[url] = path; // Notify DevTools. inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "savedURL", base::Value(url), base::Value(path.AsUTF8Unsafe())); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL", base::Value(url)); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List())); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::Value::List file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemsLoaded", base::Value(std::move(file_system_value))); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); base::Value::Dict file_system_value = CreateFileSystemValue(file_system); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); std::string error = ""; // No error inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemAdded", base::Value(error), base::Value(std::move(file_system_value))); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "fileSystemRemoved", base::Value(path)); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetListDeprecated()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::Value::Dict color; color.Set("r", r); color.Set("g", g); color.Set("b", b); color.Set("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color))); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id), base::Value(file_system_path), base::Value(total_work)); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "indexingWorked", base::Value(request_id), base::Value(file_system_path), base::Value(worked)); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone", base::Value(request_id), base::Value(file_system_path)); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::Value::List file_paths_value; for (const auto& file_path : file_paths) file_paths_value.Append(file_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI", "searchCompleted", base::Value(request_id), base::Value(file_system_path), base::Value(std::move(file_paths_value))); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) owner_window_->SetFullScreen(enter_fullscreen); UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace electron::api namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
shell/browser/api/electron_api_web_contents.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "content/common/cursors/webcursor.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/frame_subscriber.h" #include "shell/browser/api/save_page_handler.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/gin_helper/pinnable.h" #include "ui/base/models/image_model.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/mojom/view_type.mojom.h" namespace extensions { class ScriptExecutor; } #endif namespace blink { struct DeviceEmulationParams; // enum class PermissionType; } // namespace blink namespace gin_helper { class Dictionary; } namespace network { class ResourceRequestBody; } namespace gin { class Arguments; } class ExclusiveAccessManager; namespace electron { class ElectronBrowserContext; class ElectronJavaScriptDialogManager; class InspectableWebContents; class WebContentsZoomController; class WebViewGuestDelegate; class FrameSubscriber; class WebDialogHelper; class NativeWindow; #if BUILDFLAG(ENABLE_OSR) class OffScreenRenderWidgetHostView; class OffScreenWebContentsView; #endif namespace api { // Wrapper around the content::WebContents. class WebContents : public ExclusiveAccessContext, public gin::Wrappable<WebContents>, public gin_helper::EventEmitterMixin<WebContents>, public gin_helper::Constructible<WebContents>, public gin_helper::Pinnable<WebContents>, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: enum class Type { kBackgroundPage, // An extension background page. kBrowserWindow, // Used by BrowserWindow. kBrowserView, // Used by BrowserView. kRemote, // Thin wrap around an existing WebContents. kWebView, // Used by <webview>. kOffScreen, // Used for offscreen rendering }; // Create a new WebContents and return the V8 wrapper of it. static gin::Handle<WebContents> New(v8::Isolate* isolate, const gin_helper::Dictionary& options); // Create a new V8 wrapper for an existing |web_content|. // // The lifetime of |web_contents| will be managed by this class. static gin::Handle<WebContents> CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Get the api::WebContents associated with |web_contents|. Returns nullptr // if there is no associated wrapper. static WebContents* From(content::WebContents* web_contents); static WebContents* FromID(int32_t id); // Get the V8 wrapper of the |web_contents|, or create one if not existed. // // The lifetime of |web_contents| is NOT managed by this class, and the type // of this wrapper is always REMOTE. static gin::Handle<WebContents> FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents); static gin::Handle<WebContents> CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); const char* GetTypeName() override; void Destroy(); base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } bool GetBackgroundThrottling() const; void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; Type GetType() const; bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); void ReloadIgnoringCache(); void DownloadURL(const GURL& url); GURL GetURL() const; std::u16string GetTitle() const; bool IsLoading() const; bool IsLoadingMainFrame() const; bool IsWaitingForResponse() const; void Stop(); bool CanGoBack() const; void GoBack(); bool CanGoForward() const; void GoForward(); bool CanGoToOffset(int offset) const; void GoToOffset(int offset); bool CanGoToIndex(int index) const; void GoToIndex(int index); int GetActiveIndex() const; void ClearHistory(); int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); void SetUserAgent(const std::string& user_agent); std::string GetUserAgent(); void InsertCSS(const std::string& css); v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path, const content::SavePageType& save_type); void OpenDevTools(gin::Arguments* args); void CloseDevTools(); bool IsDevToolsOpened(); bool IsDevToolsFocused(); void ToggleDevTools(); void EnableDeviceEmulation(const blink::DeviceEmulationParams& params); void DisableDeviceEmulation(); void InspectElement(int x, int y); void InspectSharedWorker(); void InspectSharedWorkerById(const std::string& workerId); std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers(); void InspectServiceWorker(); void SetIgnoreMenuShortcuts(bool ignore); void SetAudioMuted(bool muted); bool IsAudioMuted(); bool IsCurrentlyAudible(); void SetEmbedder(const WebContents* embedder); void SetDevToolsWebContents(const WebContents* devtools); v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const; void IncrementCapturerCount(gin::Arguments* args); void DecrementCapturerCount(gin::Arguments* args); bool IsBeingCaptured(); void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host); #if BUILDFLAG(ENABLE_PRINTING) void OnGetDeviceNameToUse(base::Value::Dict print_settings, printing::CompletionCallback print_callback, bool silent, // <error, device_name> std::pair<std::string, std::u16string> info); void Print(gin::Arguments* args); // Print current page as PDF. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings); void OnPDFCreated(gin_helper::Promise<v8::Local<v8::Value>> promise, PrintViewManagerElectron::PrintResult print_result, scoped_refptr<base::RefCountedMemory> data); #endif void SetNextChildWebPreferences(const gin_helper::Dictionary); // DevTools workspace api. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path); void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path); // Editing commands. void Undo(); void Redo(); void Cut(); void Copy(); void Paste(); void PasteAndMatchStyle(); void Delete(); void SelectAll(); void Unselect(); void Replace(const std::u16string& word); void ReplaceMisspelling(const std::u16string& word); uint32_t FindInPage(gin::Arguments* args); void StopFindInPage(content::StopFindAction action); void ShowDefinitionForSelection(); void CopyImageAt(int x, int y); // Focus. void Focus(); bool IsFocused() const; // Send WebInputEvent to the page. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event); // Subscribe to the frame updates. void BeginFrameSubscription(gin::Arguments* args); void EndFrameSubscription(); // Dragging native items. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args); // Captures the page with |rect|, |callback| would be called when capturing is // done. v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. bool IsGuest() const; void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); // Methods for offscreen rendering bool IsOffScreen() const; #if BUILDFLAG(ENABLE_OSR) void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); void StartPainting(); void StopPainting(); bool IsPainting() const; void SetFrameRate(int frame_rate); int GetFrameRate() const; #endif void Invalidate(); gfx::Size GetSizeForNewRenderView(content::WebContents*) override; // Methods for zoom handling. void SetZoomLevel(double level); double GetZoomLevel() const; void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor); double GetZoomFactor() const; // Callback triggered on permission response. void OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed); // Create window with the given disposition. void 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); // Returns the preload script path of current WebContents. std::vector<base::FilePath> GetPreloadPaths() const; // Returns the web preferences of current WebContents. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const; // Returns the owner window. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const; // Notifies the web page that there is user interaction. void NotifyUserActivation(); v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate, const base::FilePath& file_path); v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate); // Properties. int32_t ID() const { return id_; } v8::Local<v8::Value> Session(v8::Isolate* isolate); content::WebContents* HostWebContents() const; v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate); v8::Local<v8::Value> Debugger(v8::Isolate* isolate); content::RenderFrameHost* MainFrame(); WebContentsZoomController* GetZoomController() { return zoom_controller_; } void AddObserver(ExtendedWebContentsObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(ExtendedWebContentsObserver* obs) { // Trying to remove from an empty collection leads to an access violation if (!observers_.empty()) observers_.RemoveObserver(obs); } bool EmitNavigationEvent(const std::string& event, content::NavigationHandle* navigation_handle); // this.emit(name, new Event(sender, message), args...); template <typename... Args> bool EmitWithSender(base::StringPiece name, content::RenderFrameHost* sender, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return false; v8::Local<v8::Object> event = gin_helper::internal::CreateNativeEvent( isolate, wrapper, sender, std::move(callback)); return EmitCustomEvent(name, event, std::forward<Args>(args)...); } WebContents* embedder() { return embedder_; } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ScriptExecutor* script_executor() { return script_executor_.get(); } #endif // Set the window as owner window. void SetOwnerWindow(NativeWindow* owner_window); void SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window); // Returns the WebContents managed by this delegate. content::WebContents* GetWebContents() const; // Returns the WebContents of devtools. content::WebContents* GetDevToolsWebContents() const; InspectableWebContents* inspectable_web_contents() const { return inspectable_web_contents_.get(); } NativeWindow* owner_window() const { return owner_window_.get(); } bool is_html_fullscreen() const { return html_fullscreen_; } void set_fullscreen_frame(content::RenderFrameHost* rfh) { fullscreen_frame_ = rfh; } // mojom::ElectronApiIPC void Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); void Invoke(bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::InvokeCallback callback, content::RenderFrameHost* render_frame_host); void ReceivePostMessage(const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host); void MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronApiIPC::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host); void MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments); void MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host); // mojom::ElectronWebContentsUtility void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host); void UpdateDraggableRegions(std::vector<mojom::DraggableRegionPtr> regions); void SetTemporaryZoomLevel(double level); void DoGetZoomLevel( electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback callback); void SetImageAnimationPolicy(const std::string& new_policy); // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; private: // Does not manage lifetime of |web_contents|. WebContents(v8::Isolate* isolate, content::WebContents* web_contents); // Takes over ownership of |web_contents|. WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type); // Creates a new content::WebContents. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options); ~WebContents() override; // Delete this if garbage collection has not started. void DeleteThisIfAlive(); // Creates a InspectableWebContents object and takes ownership of // |web_contents|. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest); void InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, gin::Handle<class Session> session, const gin_helper::Dictionary& options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type); #endif // content::WebContentsDelegate: bool DidAddMessageToConsole(content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) override; bool IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) override; content::WebContents* CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionConfig& partition_config, content::SessionStorageNamespace* session_storage_namespace) override; void WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) override; void AddNewContents(content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& window_features, bool user_gesture, bool* was_blocked) override; content::WebContents* OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) override; void BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) override; void SetContentsBounds(content::WebContents* source, const gfx::Rect& pos) override; void CloseContents(content::WebContents* source) override; void ActivateContents(content::WebContents* contents) override; void UpdateTargetURL(content::WebContents* source, const GURL& url) override; bool HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; bool PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event); content::KeyboardEventProcessingResult PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; void ContentsZoomChange(bool zoom_in) override; void EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) override; void ExitFullscreenModeForTab(content::WebContents* source) override; void RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) override; void RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) override; bool HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) override; void FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) override; void RequestExclusivePointerAccess(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed); void RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) override; void LostMouseLock() override; void RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) override; void CancelKeyboardLockRequest(content::WebContents* web_contents) override; bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) override; void RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) override; content::JavaScriptDialogManager* GetJavaScriptDialogManager( content::WebContents* source) override; void OnAudioStateChanged(bool audible) override; void UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) override; // content::WebContentsObserver: void BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) override; void OnBackgroundColorChanged() override; void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override; void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void FrameDeleted(int frame_tree_node_id) override; void RenderViewDeleted(content::RenderViewHost*) override; void PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) override; void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; void DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url, int error_code) override; void DidStartLoading() override; void DidStopLoading() override; void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidRedirectNavigation( content::NavigationHandle* navigation_handle) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void WebContentsDestroyed() override; void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void TitleWasSet(content::NavigationEntry* entry) override; void DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) override; void PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) override; void MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) override; void DidChangeThemeColor() override; void OnCursorChanged(const content::WebCursor& cursor) override; void DidAcquireFullscreen(content::RenderFrameHost* rfh) override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; // InspectableWebContentsViewDelegate: void DevToolsFocused() override; void DevToolsOpened() override; void DevToolsClosed() override; void DevToolsResized() override; ElectronBrowserContext* GetBrowserContext() const; void OnElectronBrowserConnectionError(); #if BUILDFLAG(ENABLE_OSR) OffScreenWebContentsView* GetOffScreenWebContentsView() const; OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const; #endif // Called when received a synchronous message from renderer to // get the zoom level. void OnGetZoomLevel(content::RenderFrameHost* frame_host, IPC::Message* reply_msg); void InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options); // content::WebContentsDelegate: bool CanOverscrollContent() override; std::unique_ptr<content::EyeDropper> OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; // ExclusiveAccessContext: Profile* GetProfile() override; bool IsFullscreen() const override; void EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) override; void ExitFullscreen() override; void UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool notify_download, bool force_update) override; void OnExclusiveAccessUserInput() override; content::WebContents* GetActiveWebContents() override; bool CanUserExitFullscreen() const override; bool IsExclusiveAccessBubbleDisplayed() const override; bool IsFullscreenForTabOrPending(const content::WebContents* source) override; bool TakeFocus(content::WebContents* source, bool reverse) override; content::PictureInPictureResult EnterPictureInPicture( content::WebContents* web_contents) override; void ExitPictureInPicture() override; // InspectableWebContentsDelegate: void DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) override; void DevToolsAppendToFile(const std::string& url, const std::string& content) override; void DevToolsRequestFileSystems() override; void DevToolsAddFileSystem(const std::string& type, const base::FilePath& file_system_path) override; void DevToolsRemoveFileSystem( const base::FilePath& file_system_path) override; void DevToolsIndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) override; void DevToolsStopIndexing(int request_id) override; void DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) override; void DevToolsSetEyeDropperActive(bool active) override; // InspectableWebContentsViewDelegate: #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel GetDevToolsWindowIcon() override; #endif #if BUILDFLAG(IS_LINUX) void GetDevToolsWindowWMClass(std::string* name, std::string* class_name) override; #endif void ColorPickedInEyeDropper(int r, int g, int b, int a); // DevTools index event callbacks. void OnDevToolsIndexingWorkCalculated(int request_id, const std::string& file_system_path, int total_work); void OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked); void OnDevToolsIndexingDone(int request_id, const std::string& file_system_path); void OnDevToolsSearchCompleted(int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths); // Set fullscreen mode triggered by html api. void SetHtmlApiFullscreen(bool enter_fullscreen); // Update the html fullscreen flag in both browser and renderer. void UpdateHtmlApiFullscreen(bool fullscreen); v8::Global<v8::Value> session_; v8::Global<v8::Value> devtools_web_contents_; v8::Global<v8::Value> debugger_; std::unique_ptr<ElectronJavaScriptDialogManager> dialog_manager_; std::unique_ptr<WebViewGuestDelegate> guest_delegate_; std::unique_ptr<FrameSubscriber> frame_subscriber_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<extensions::ScriptExecutor> script_executor_; #endif // The host webcontents that may contain this webcontents. WebContents* embedder_ = nullptr; // Whether the guest view has been attached. bool attached_ = false; // The zoom controller for this webContents. WebContentsZoomController* zoom_controller_ = nullptr; // The type of current WebContents. Type type_ = Type::kBrowserWindow; int32_t id_; // Request id used for findInPage request. uint32_t find_in_page_request_id_ = 0; // Whether background throttling is disabled. bool background_throttling_ = true; // Whether to enable devtools. bool enable_devtools_ = true; // Observers of this WebContents. base::ObserverList<ExtendedWebContentsObserver> observers_; v8::Global<v8::Value> pending_child_web_preferences_; // The window that this WebContents belongs to. base::WeakPtr<NativeWindow> owner_window_; bool offscreen_ = false; // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; // Whether window is fullscreened by window api. bool native_fullscreen_ = false; scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; ElectronBrowserContext* browser_context_; // The stored InspectableWebContents object. // Notice that inspectable_web_contents_ must be placed after // dialog_manager_, so we can make sure inspectable_web_contents_ is // destroyed before dialog_manager_, otherwise a crash would happen. std::unique_ptr<InspectableWebContents> inspectable_web_contents_; // Maps url to file path, used by the file requests sent from devtools. typedef std::map<std::string, base::FilePath> PathsMap; PathsMap saved_files_; // Map id to index job, used for file system indexing requests from devtools. typedef std:: map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>> DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_; #if BUILDFLAG(ENABLE_PRINTING) scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none. content::RenderFrameHost* fullscreen_frame_ = nullptr; base::WeakPtrFactory<WebContents> weak_factory_{this}; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
26,929
API: Documented way to close a WebContents
There should be a documented way to close a WebContents and allow it to be garbage collected. I'd prefer not to document the existing `webContents.destroy()` method if possible as it's quite aggressive and makes the underlying WebContents object unusable after being called. Ideally, I'd like to have a `webContents.close()` method that returns the object to the state that it was in prior to `loadURL()` being called, and marks it as available for GC once references are dropped. i.e. this should work: ```js const bv = new BrowserView bv.webContents.loadURL("https://example.com") // ... later ... bv.webContents.close() // If the reference to `bv` were dropped here, both `bv` and the webContents would be available for collection // ... but if the reference is retained, the WebContents should be re-usable at a later date: bv.webContents.loadURL("https://example.com") ``` Ref https://github.com/electron/electron/pull/23578.
https://github.com/electron/electron/issues/26929
https://github.com/electron/electron/pull/35509
994834d25a7060c05e89f0e5476eda832c957abc
eebf34cc6c4691e2ddca9b5a0a97566aeabd9072
2020-12-10T18:55:02Z
c++
2022-09-16T23:22:59Z
spec/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); it('fails when an invalid deviceName is passed', (done) => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => { expect(success).to.equal(false); expect(reason).to.match(/Invalid deviceName provided/); done(); }); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('does not crash when loading a new URL with emulation settings set', async () => { const setEmulation = async () => { if (w.webContents) { w.webContents.debugger.attach('1.3'); const deviceMetrics = { width: 700, height: 600, deviceScaleFactor: 2, mobile: true, dontSetVisibleSize: true }; await w.webContents.debugger.sendCommand( 'Emulation.setDeviceMetricsOverride', deviceMetrics ); } }; try { await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await setEmulation(); await w.loadURL('data:text/html,<h1>HELLO</h1>'); await setEmulation(); } catch (e) { expect((e as Error).message).to.match(/Debugger is already attached to the target/); } }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus APIs', () => { describe('focus()', () => { afterEach(closeAllWindows); it('does not blur the focused window when the web contents is hidden', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); const moveFocusToDevTools = async (win: BrowserWindow) => { const devToolsOpened = emittedOnce(win.webContents, 'devtools-opened'); win.webContents.openDevTools({ mode: 'right' }); await devToolsOpened; win.webContents.devToolsWebContents!.focus(); }; describe('focus event', () => { afterEach(closeAllWindows); it('is triggered when web contents is focused', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await moveFocusToDevTools(w); const focusPromise = emittedOnce(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).to.eventually.be.fulfilled(); }); it('is triggered when BrowserWindow is focused', async () => { const window1 = new BrowserWindow({ show: false }); const window2 = new BrowserWindow({ show: false }); await Promise.all([ window1.loadURL('about:blank'), window2.loadURL('about:blank') ]); const focusPromise1 = emittedOnce(window1.webContents, 'focus'); const focusPromise2 = emittedOnce(window2.webContents, 'focus'); window1.showInactive(); window2.showInactive(); window1.focus(); await expect(focusPromise1).to.eventually.be.fulfilled(); window2.focus(); await expect(focusPromise2).to.eventually.be.fulfilled(); }); }); describe('blur event', () => { afterEach(closeAllWindows); it('is triggered when web contents is blurred', async () => { const w = new BrowserWindow({ show: true }); await w.loadURL('about:blank'); w.webContents.focus(); const blurPromise = emittedOnce(w.webContents, 'blur'); await moveFocusToDevTools(w); await expect(blurPromise).to.eventually.be.fulfilled(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid process id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('is not empty by default', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); expect(userAgent).to.be.a('string').that.is.not.empty(); }); it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { expect(details.referrer.url).to.equal(url); expect(details.referrer.policy).to.equal('no-referrer-when-downgrade'); return { action: 'allow' }; }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { landscape: [], displayHeaderFooter: '123', printBackground: 2, scale: 'not-a-number', pageSize: 'IAmAPageSize', margins: 'terrible', pageRanges: { oops: 'im-not-the-right-key' }, headerTemplate: [1, 2, 3], footerTemplate: [4, 5, 6], preferCSSPageSize: 'no' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); describe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: '1-3', landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); describe('content-bounds-updated event', () => { afterEach(closeAllWindows); it('emits when moveTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.moveTo(100, 100)', true); const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated'); const { width, height } = w.getBounds(); expect(rect).to.deep.equal({ x: 100, y: 100, width, height }); await new Promise(setImmediate); expect(w.getBounds().x).to.equal(100); expect(w.getBounds().y).to.equal(100); }); it('emits when resizeTo is called', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated'); const { x, y } = w.getBounds(); expect(rect).to.deep.equal({ x, y, width: 100, height: 100 }); await new Promise(setImmediate); expect({ width: w.getBounds().width, height: w.getBounds().height }).to.deep.equal(process.platform === 'win32' ? { // The width is reported as being larger on Windows? I'm not sure why // this is. width: 136, height: 100 } : { width: 100, height: 100 }); }); it('does not change window bounds if cancelled', async () => { const w = new BrowserWindow({ show: false }); const { width, height } = w.getBounds(); w.loadURL('about:blank'); w.webContents.once('content-bounds-updated', e => e.preventDefault()); await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true); await new Promise(setImmediate); expect(w.getBounds().width).to.equal(width); expect(w.getBounds().height).to.equal(height); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,588
[Feature Request]: `contextBridge.exposeInIsolatedWorld`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description I am working on application's plugin/add-on system and I want to disallow from plugins/add-ons doing anything without user giving permissions to them. This can work great with isolated worlds, but isolated worlds still lack things. Node's `vm` feels more powerful than Electron's isolated worlds, but Node's `vm` doesn't work great with Electron. You can't really set isolated world's window variables either without using hacks like executing JS in isolated world to set its window variables, which will make you struggle implementing functions properly. ### Proposed Solution The introduction of `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`. This would allow you to set isolated world's window properties and would be similar to `contextBridge.exposeInMainWorld(apiKey, api)`. Example: ```js webFrame.setIsolatedWorldInfo(1005, { name: "Isolated World 5" }); contextBridge.exposeInIsolatedWorld(1005, "api", { doStuff() { console.log("Isolated World 5 is doing stuff"); } }); await webFrame.executeJavaScriptInIsolatedWorld(1005, [ { "code": "window.api.doStuff()" } ]); ``` Console Output: ``` -> Isolated World 5 is doing stuff ``` ### Alternatives Considered `webFrame.setIsolatedWorldInfo` could allow setting window variables for that isolated world. ### Additional Information _No response_
https://github.com/electron/electron/issues/32588
https://github.com/electron/electron/pull/34974
8c3c0f0b50634bd62c1a4c9a826d8c7aad329c11
dfc134de4286307e61d61f8b6c9ac6a984aed50f
2022-01-23T18:49:51Z
c++
2022-09-21T18:17:10Z
docs/api/context-bridge.md
# contextBridge > Create a safe, bi-directional, synchronous bridge across isolated contexts Process: [Renderer](../glossary.md#renderer-process) An example of exposing an API to a renderer from an isolated preload script is given below: ```javascript // Preload (Isolated World) const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) ``` ```javascript // Renderer (Main World) window.electron.doThing() ``` ## Glossary ### Main World The "Main World" is the JavaScript context that your main renderer code runs in. By default, the page you load in your renderer executes code in this world. ### Isolated World When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an "Isolated World". You can read more about context isolation and what it affects in the [security](../tutorial/security.md#3-enable-context-isolation) docs. ## Methods The `contextBridge` module has the following methods: ### `contextBridge.exposeInMainWorld(apiKey, api)` * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. ## Usage ### API The `api` provided to [`exposeInMainWorld`](#contextbridgeexposeinmainworldapikey-api) must be a `Function`, `string`, `number`, `Array`, `boolean`, or an object whose keys are strings and values are a `Function`, `string`, `number`, `Array`, `boolean`, or another nested object that meets the same conditions. `Function` values are proxied to the other context and all other values are **copied** and **frozen**. Any data / primitives sent in the API become immutable and updates on either side of the bridge do not result in an update on the other side. An example of a complex API is shown below: ```javascript const { contextBridge } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing'), myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))], anAsyncFunction: async () => 123, data: { myFlags: ['a', 'b', 'c'], bootTime: 1234 }, nestedAPI: { evenDeeper: { youCanDoThisAsMuchAsYouWant: { fn: () => ({ returnData: 123 }) } } } } ) ``` ### API Functions `Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This results in some key limitations that we've outlined below. #### Parameter / Error / Return Type support Because parameters, errors and return values are **copied** when they are sent over the bridge, there are only certain types that can be used. At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. A table of type support has been included below for completeness: | Type | Complexity | Parameter Support | Return Value Support | Limitations | | ---- | ---------- | ----------------- | -------------------- | ----------- | | `string` | Simple | ✅ | ✅ | N/A | | `number` | Simple | ✅ | ✅ | N/A | | `boolean` | Simple | ✅ | ✅ | N/A | | `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. | | `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type | | `Error` | Complex | ✅ | ✅ | Errors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context, and any custom properties on the Error object [will be lost](https://github.com/electron/electron/issues/25596) | | `Promise` | Complex | ✅ | ✅ | N/A | `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. | | [Cloneable Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) | Simple | ✅ | ✅ | See the linked document on cloneable types | | `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. | | `Blob` | Complex | ✅ | ✅ | N/A | | `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped | If the type you care about is not in the above table, it is probably not supported. ### Exposing Node Global Symbols The `contextBridge` can be used by the preload script to give your renderer access to Node APIs. The table of supported types described above also applies to Node APIs that you expose through `contextBridge`. Please note that many Node APIs grant access to local system resources. Be very cautious about which globals and APIs you expose to untrusted remote content. ```javascript const { contextBridge } = require('electron') const crypto = require('crypto') contextBridge.exposeInMainWorld('nodeCrypto', { sha256sum (data) { const hash = crypto.createHash('sha256') hash.update(data) return hash.digest('hex') } }) ```
closed
electron/electron
https://github.com/electron/electron
32,588
[Feature Request]: `contextBridge.exposeInIsolatedWorld`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description I am working on application's plugin/add-on system and I want to disallow from plugins/add-ons doing anything without user giving permissions to them. This can work great with isolated worlds, but isolated worlds still lack things. Node's `vm` feels more powerful than Electron's isolated worlds, but Node's `vm` doesn't work great with Electron. You can't really set isolated world's window variables either without using hacks like executing JS in isolated world to set its window variables, which will make you struggle implementing functions properly. ### Proposed Solution The introduction of `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`. This would allow you to set isolated world's window properties and would be similar to `contextBridge.exposeInMainWorld(apiKey, api)`. Example: ```js webFrame.setIsolatedWorldInfo(1005, { name: "Isolated World 5" }); contextBridge.exposeInIsolatedWorld(1005, "api", { doStuff() { console.log("Isolated World 5 is doing stuff"); } }); await webFrame.executeJavaScriptInIsolatedWorld(1005, [ { "code": "window.api.doStuff()" } ]); ``` Console Output: ``` -> Isolated World 5 is doing stuff ``` ### Alternatives Considered `webFrame.setIsolatedWorldInfo` could allow setting window variables for that isolated world. ### Additional Information _No response_
https://github.com/electron/electron/issues/32588
https://github.com/electron/electron/pull/34974
8c3c0f0b50634bd62c1a4c9a826d8c7aad329c11
dfc134de4286307e61d61f8b6c9ac6a984aed50f
2022-01-23T18:49:51Z
c++
2022-09-21T18:17:10Z
filenames.auto.gni
# THIS FILE IS AUTO-GENERATED, PLEASE DO NOT EDIT BY HAND auto_filenames = { api_docs = [ "docs/api/accelerator.md", "docs/api/app.md", "docs/api/auto-updater.md", "docs/api/browser-view.md", "docs/api/browser-window.md", "docs/api/client-request.md", "docs/api/clipboard.md", "docs/api/command-line-switches.md", "docs/api/command-line.md", "docs/api/content-tracing.md", "docs/api/context-bridge.md", "docs/api/cookies.md", "docs/api/crash-reporter.md", "docs/api/debugger.md", "docs/api/desktop-capturer.md", "docs/api/dialog.md", "docs/api/dock.md", "docs/api/download-item.md", "docs/api/environment-variables.md", "docs/api/extensions.md", "docs/api/file-object.md", "docs/api/global-shortcut.md", "docs/api/in-app-purchase.md", "docs/api/incoming-message.md", "docs/api/ipc-main.md", "docs/api/ipc-renderer.md", "docs/api/menu-item.md", "docs/api/menu.md", "docs/api/message-channel-main.md", "docs/api/message-port-main.md", "docs/api/native-image.md", "docs/api/native-theme.md", "docs/api/net-log.md", "docs/api/net.md", "docs/api/notification.md", "docs/api/power-monitor.md", "docs/api/power-save-blocker.md", "docs/api/process.md", "docs/api/protocol.md", "docs/api/push-notifications.md", "docs/api/safe-storage.md", "docs/api/screen.md", "docs/api/service-workers.md", "docs/api/session.md", "docs/api/share-menu.md", "docs/api/shell.md", "docs/api/structures", "docs/api/synopsis.md", "docs/api/system-preferences.md", "docs/api/touch-bar-button.md", "docs/api/touch-bar-color-picker.md", "docs/api/touch-bar-group.md", "docs/api/touch-bar-label.md", "docs/api/touch-bar-other-items-proxy.md", "docs/api/touch-bar-popover.md", "docs/api/touch-bar-scrubber.md", "docs/api/touch-bar-segmented-control.md", "docs/api/touch-bar-slider.md", "docs/api/touch-bar-spacer.md", "docs/api/touch-bar.md", "docs/api/tray.md", "docs/api/web-contents.md", "docs/api/web-frame-main.md", "docs/api/web-frame.md", "docs/api/web-request.md", "docs/api/webview-tag.md", "docs/api/window-open.md", "docs/api/structures/bluetooth-device.md", "docs/api/structures/certificate-principal.md", "docs/api/structures/certificate.md", "docs/api/structures/cookie.md", "docs/api/structures/cpu-usage.md", "docs/api/structures/crash-report.md", "docs/api/structures/custom-scheme.md", "docs/api/structures/desktop-capturer-source.md", "docs/api/structures/display.md", "docs/api/structures/event.md", "docs/api/structures/extension-info.md", "docs/api/structures/extension.md", "docs/api/structures/file-filter.md", "docs/api/structures/file-path-with-headers.md", "docs/api/structures/gpu-feature-status.md", "docs/api/structures/hid-device.md", "docs/api/structures/input-event.md", "docs/api/structures/io-counters.md", "docs/api/structures/ipc-main-event.md", "docs/api/structures/ipc-main-invoke-event.md", "docs/api/structures/ipc-renderer-event.md", "docs/api/structures/jump-list-category.md", "docs/api/structures/jump-list-item.md", "docs/api/structures/keyboard-event.md", "docs/api/structures/keyboard-input-event.md", "docs/api/structures/memory-info.md", "docs/api/structures/memory-usage-details.md", "docs/api/structures/mime-typed-buffer.md", "docs/api/structures/mouse-input-event.md", "docs/api/structures/mouse-wheel-input-event.md", "docs/api/structures/notification-action.md", "docs/api/structures/notification-response.md", "docs/api/structures/payment-discount.md", "docs/api/structures/point.md", "docs/api/structures/post-body.md", "docs/api/structures/printer-info.md", "docs/api/structures/process-memory-info.md", "docs/api/structures/process-metric.md", "docs/api/structures/product-discount.md", "docs/api/structures/product-subscription-period.md", "docs/api/structures/product.md", "docs/api/structures/protocol-request.md", "docs/api/structures/protocol-response-upload-data.md", "docs/api/structures/protocol-response.md", "docs/api/structures/rectangle.md", "docs/api/structures/referrer.md", "docs/api/structures/scrubber-item.md", "docs/api/structures/segmented-control-segment.md", "docs/api/structures/serial-port.md", "docs/api/structures/service-worker-info.md", "docs/api/structures/shared-worker-info.md", "docs/api/structures/sharing-item.md", "docs/api/structures/shortcut-details.md", "docs/api/structures/size.md", "docs/api/structures/task.md", "docs/api/structures/thumbar-button.md", "docs/api/structures/trace-categories-and-options.md", "docs/api/structures/trace-config.md", "docs/api/structures/transaction.md", "docs/api/structures/upload-data.md", "docs/api/structures/upload-file.md", "docs/api/structures/upload-raw-data.md", "docs/api/structures/user-default-types.md", "docs/api/structures/web-request-filter.md", "docs/api/structures/web-source.md", ] sandbox_bundle_deps = [ "lib/common/api/native-image.ts", "lib/common/define-properties.ts", "lib/common/ipc-messages.ts", "lib/common/web-view-methods.ts", "lib/renderer/api/context-bridge.ts", "lib/renderer/api/crash-reporter.ts", "lib/renderer/api/ipc-renderer.ts", "lib/renderer/api/web-frame.ts", "lib/renderer/common-init.ts", "lib/renderer/inspector.ts", "lib/renderer/ipc-renderer-internal-utils.ts", "lib/renderer/ipc-renderer-internal.ts", "lib/renderer/security-warnings.ts", "lib/renderer/web-frame-init.ts", "lib/renderer/web-view/guest-view-internal.ts", "lib/renderer/web-view/web-view-attributes.ts", "lib/renderer/web-view/web-view-constants.ts", "lib/renderer/web-view/web-view-element.ts", "lib/renderer/web-view/web-view-impl.ts", "lib/renderer/web-view/web-view-init.ts", "lib/renderer/window-setup.ts", "lib/sandboxed_renderer/api/exports/electron.ts", "lib/sandboxed_renderer/api/module-list.ts", "lib/sandboxed_renderer/init.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] isolated_bundle_deps = [ "lib/common/web-view-methods.ts", "lib/isolated_renderer/init.ts", "lib/renderer/web-view/web-view-attributes.ts", "lib/renderer/web-view/web-view-constants.ts", "lib/renderer/web-view/web-view-element.ts", "lib/renderer/web-view/web-view-impl.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] browser_bundle_deps = [ "lib/browser/api/app.ts", "lib/browser/api/auto-updater.ts", "lib/browser/api/auto-updater/auto-updater-native.ts", "lib/browser/api/auto-updater/auto-updater-win.ts", "lib/browser/api/auto-updater/squirrel-update-win.ts", "lib/browser/api/base-window.ts", "lib/browser/api/browser-view.ts", "lib/browser/api/browser-window.ts", "lib/browser/api/content-tracing.ts", "lib/browser/api/crash-reporter.ts", "lib/browser/api/desktop-capturer.ts", "lib/browser/api/dialog.ts", "lib/browser/api/exports/electron.ts", "lib/browser/api/global-shortcut.ts", "lib/browser/api/in-app-purchase.ts", "lib/browser/api/ipc-main.ts", "lib/browser/api/menu-item-roles.ts", "lib/browser/api/menu-item.ts", "lib/browser/api/menu-utils.ts", "lib/browser/api/menu.ts", "lib/browser/api/message-channel.ts", "lib/browser/api/module-list.ts", "lib/browser/api/native-theme.ts", "lib/browser/api/net-log.ts", "lib/browser/api/net.ts", "lib/browser/api/notification.ts", "lib/browser/api/power-monitor.ts", "lib/browser/api/power-save-blocker.ts", "lib/browser/api/protocol.ts", "lib/browser/api/push-notifications.ts", "lib/browser/api/safe-storage.ts", "lib/browser/api/screen.ts", "lib/browser/api/session.ts", "lib/browser/api/share-menu.ts", "lib/browser/api/system-preferences.ts", "lib/browser/api/touch-bar.ts", "lib/browser/api/tray.ts", "lib/browser/api/view.ts", "lib/browser/api/views/image-view.ts", "lib/browser/api/web-contents-view.ts", "lib/browser/api/web-contents.ts", "lib/browser/api/web-frame-main.ts", "lib/browser/default-menu.ts", "lib/browser/devtools.ts", "lib/browser/guest-view-manager.ts", "lib/browser/guest-window-manager.ts", "lib/browser/init.ts", "lib/browser/ipc-main-impl.ts", "lib/browser/ipc-main-internal-utils.ts", "lib/browser/ipc-main-internal.ts", "lib/browser/message-port-main.ts", "lib/browser/parse-features-string.ts", "lib/browser/rpc-server.ts", "lib/browser/web-view-events.ts", "lib/common/api/clipboard.ts", "lib/common/api/module-list.ts", "lib/common/api/native-image.ts", "lib/common/api/shell.ts", "lib/common/define-properties.ts", "lib/common/deprecate.ts", "lib/common/init.ts", "lib/common/ipc-messages.ts", "lib/common/reset-search-paths.ts", "lib/common/web-view-methods.ts", "lib/common/webpack-globals-provider.ts", "lib/renderer/ipc-renderer-internal-utils.ts", "lib/renderer/ipc-renderer-internal.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] renderer_bundle_deps = [ "lib/common/api/clipboard.ts", "lib/common/api/module-list.ts", "lib/common/api/native-image.ts", "lib/common/api/shell.ts", "lib/common/define-properties.ts", "lib/common/init.ts", "lib/common/ipc-messages.ts", "lib/common/reset-search-paths.ts", "lib/common/web-view-methods.ts", "lib/common/webpack-provider.ts", "lib/renderer/api/context-bridge.ts", "lib/renderer/api/crash-reporter.ts", "lib/renderer/api/exports/electron.ts", "lib/renderer/api/ipc-renderer.ts", "lib/renderer/api/module-list.ts", "lib/renderer/api/web-frame.ts", "lib/renderer/common-init.ts", "lib/renderer/init.ts", "lib/renderer/inspector.ts", "lib/renderer/ipc-renderer-internal-utils.ts", "lib/renderer/ipc-renderer-internal.ts", "lib/renderer/security-warnings.ts", "lib/renderer/web-frame-init.ts", "lib/renderer/web-view/guest-view-internal.ts", "lib/renderer/web-view/web-view-attributes.ts", "lib/renderer/web-view/web-view-constants.ts", "lib/renderer/web-view/web-view-element.ts", "lib/renderer/web-view/web-view-impl.ts", "lib/renderer/web-view/web-view-init.ts", "lib/renderer/window-setup.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] worker_bundle_deps = [ "lib/common/api/clipboard.ts", "lib/common/api/module-list.ts", "lib/common/api/native-image.ts", "lib/common/api/shell.ts", "lib/common/define-properties.ts", "lib/common/init.ts", "lib/common/ipc-messages.ts", "lib/common/reset-search-paths.ts", "lib/common/webpack-provider.ts", "lib/renderer/api/context-bridge.ts", "lib/renderer/api/crash-reporter.ts", "lib/renderer/api/exports/electron.ts", "lib/renderer/api/ipc-renderer.ts", "lib/renderer/api/module-list.ts", "lib/renderer/api/web-frame.ts", "lib/renderer/ipc-renderer-internal-utils.ts", "lib/renderer/ipc-renderer-internal.ts", "lib/worker/init.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] asar_bundle_deps = [ "lib/asar/fs-wrapper.ts", "lib/asar/init.ts", "lib/common/webpack-provider.ts", "package.json", "tsconfig.electron.json", "tsconfig.json", "typings/internal-ambient.d.ts", "typings/internal-electron.d.ts", ] }
closed
electron/electron
https://github.com/electron/electron
32,588
[Feature Request]: `contextBridge.exposeInIsolatedWorld`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description I am working on application's plugin/add-on system and I want to disallow from plugins/add-ons doing anything without user giving permissions to them. This can work great with isolated worlds, but isolated worlds still lack things. Node's `vm` feels more powerful than Electron's isolated worlds, but Node's `vm` doesn't work great with Electron. You can't really set isolated world's window variables either without using hacks like executing JS in isolated world to set its window variables, which will make you struggle implementing functions properly. ### Proposed Solution The introduction of `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`. This would allow you to set isolated world's window properties and would be similar to `contextBridge.exposeInMainWorld(apiKey, api)`. Example: ```js webFrame.setIsolatedWorldInfo(1005, { name: "Isolated World 5" }); contextBridge.exposeInIsolatedWorld(1005, "api", { doStuff() { console.log("Isolated World 5 is doing stuff"); } }); await webFrame.executeJavaScriptInIsolatedWorld(1005, [ { "code": "window.api.doStuff()" } ]); ``` Console Output: ``` -> Isolated World 5 is doing stuff ``` ### Alternatives Considered `webFrame.setIsolatedWorldInfo` could allow setting window variables for that isolated world. ### Additional Information _No response_
https://github.com/electron/electron/issues/32588
https://github.com/electron/electron/pull/34974
8c3c0f0b50634bd62c1a4c9a826d8c7aad329c11
dfc134de4286307e61d61f8b6c9ac6a984aed50f
2022-01-23T18:49:51Z
c++
2022-09-21T18:17:10Z
lib/renderer/api/context-bridge.ts
const binding = process._linkedBinding('electron_renderer_context_bridge'); const checkContextIsolationEnabled = () => { if (!process.contextIsolated) throw new Error('contextBridge API can only be used when contextIsolation is enabled'); }; const contextBridge: Electron.ContextBridge = { exposeInMainWorld: (key: string, api: any) => { checkContextIsolationEnabled(); return binding.exposeAPIInMainWorld(key, api); } }; export default contextBridge; export const internalContextBridge = { contextIsolationEnabled: process.contextIsolated, overrideGlobalValueFromIsolatedWorld: (keys: string[], value: any) => { return binding._overrideGlobalValueFromIsolatedWorld(keys, value, false); }, overrideGlobalValueWithDynamicPropsFromIsolatedWorld: (keys: string[], value: any) => { return binding._overrideGlobalValueFromIsolatedWorld(keys, value, true); }, overrideGlobalPropertyFromIsolatedWorld: (keys: string[], getter: Function, setter?: Function) => { return binding._overrideGlobalPropertyFromIsolatedWorld(keys, getter, setter || null); }, isInMainWorld: () => binding._isCalledFromMainWorld() as boolean }; if (binding._isDebug) { contextBridge.internalContextBridge = internalContextBridge; }
closed
electron/electron
https://github.com/electron/electron
32,588
[Feature Request]: `contextBridge.exposeInIsolatedWorld`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description I am working on application's plugin/add-on system and I want to disallow from plugins/add-ons doing anything without user giving permissions to them. This can work great with isolated worlds, but isolated worlds still lack things. Node's `vm` feels more powerful than Electron's isolated worlds, but Node's `vm` doesn't work great with Electron. You can't really set isolated world's window variables either without using hacks like executing JS in isolated world to set its window variables, which will make you struggle implementing functions properly. ### Proposed Solution The introduction of `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`. This would allow you to set isolated world's window properties and would be similar to `contextBridge.exposeInMainWorld(apiKey, api)`. Example: ```js webFrame.setIsolatedWorldInfo(1005, { name: "Isolated World 5" }); contextBridge.exposeInIsolatedWorld(1005, "api", { doStuff() { console.log("Isolated World 5 is doing stuff"); } }); await webFrame.executeJavaScriptInIsolatedWorld(1005, [ { "code": "window.api.doStuff()" } ]); ``` Console Output: ``` -> Isolated World 5 is doing stuff ``` ### Alternatives Considered `webFrame.setIsolatedWorldInfo` could allow setting window variables for that isolated world. ### Additional Information _No response_
https://github.com/electron/electron/issues/32588
https://github.com/electron/electron/pull/34974
8c3c0f0b50634bd62c1a4c9a826d8c7aad329c11
dfc134de4286307e61d61f8b6c9ac6a984aed50f
2022-01-23T18:49:51Z
c++
2022-09-21T18:17:10Z
shell/renderer/api/electron_api_context_bridge.cc
// Copyright (c) 2019 Slack Technologies, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/api/electron_api_context_bridge.h" #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "base/feature_list.h" #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "base/trace_event/trace_event.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "shell/common/api/object_life_monitor.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/node_includes.h" #include "shell/common/world_ids.h" #include "third_party/blink/public/web/web_blob.h" #include "third_party/blink/public/web/web_element.h" #include "third_party/blink/public/web/web_local_frame.h" namespace features { const base::Feature kContextBridgeMutability{"ContextBridgeMutability", base::FEATURE_DISABLED_BY_DEFAULT}; } namespace electron { content::RenderFrame* GetRenderFrame(v8::Local<v8::Object> value); namespace api { namespace context_bridge { const char kProxyFunctionPrivateKey[] = "electron_contextBridge_proxy_fn"; const char kSupportsDynamicPropertiesPrivateKey[] = "electron_contextBridge_supportsDynamicProperties"; const char kOriginalFunctionPrivateKey[] = "electron_contextBridge_original_fn"; } // namespace context_bridge namespace { static int kMaxRecursion = 1000; // Returns true if |maybe| is both a value, and that value is true. inline bool IsTrue(v8::Maybe<bool> maybe) { return maybe.IsJust() && maybe.FromJust(); } // Sourced from "extensions/renderer/v8_schema_registry.cc" // Recursively freezes every v8 object on |object|. bool DeepFreeze(const v8::Local<v8::Object>& object, const v8::Local<v8::Context>& context, std::set<int> frozen = std::set<int>()) { int hash = object->GetIdentityHash(); if (frozen.find(hash) != frozen.end()) return true; frozen.insert(hash); v8::Local<v8::Array> property_names = object->GetOwnPropertyNames(context).ToLocalChecked(); for (uint32_t i = 0; i < property_names->Length(); ++i) { v8::Local<v8::Value> child = object->Get(context, property_names->Get(context, i).ToLocalChecked()) .ToLocalChecked(); if (child->IsObject() && !child->IsTypedArray()) { if (!DeepFreeze(child.As<v8::Object>(), context, frozen)) return false; } } return IsTrue( object->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen)); } bool IsPlainObject(const v8::Local<v8::Value>& object) { if (!object->IsObject()) return false; return !(object->IsNullOrUndefined() || object->IsDate() || object->IsArgumentsObject() || object->IsBigIntObject() || object->IsBooleanObject() || object->IsNumberObject() || object->IsStringObject() || object->IsSymbolObject() || object->IsNativeError() || object->IsRegExp() || object->IsPromise() || object->IsMap() || object->IsSet() || object->IsMapIterator() || object->IsSetIterator() || object->IsWeakMap() || object->IsWeakSet() || object->IsArrayBuffer() || object->IsArrayBufferView() || object->IsArray() || object->IsDataView() || object->IsSharedArrayBuffer() || object->IsProxy() || object->IsWasmModuleObject() || object->IsWasmMemoryObject() || object->IsModuleNamespaceObject()); } bool IsPlainArray(const v8::Local<v8::Value>& arr) { if (!arr->IsArray()) return false; return !arr->IsTypedArray(); } void SetPrivate(v8::Local<v8::Context> context, v8::Local<v8::Object> target, const std::string& key, v8::Local<v8::Value> value) { target ->SetPrivate( context, v8::Private::ForApi(context->GetIsolate(), gin::StringToV8(context->GetIsolate(), key)), value) .Check(); } v8::MaybeLocal<v8::Value> GetPrivate(v8::Local<v8::Context> context, v8::Local<v8::Object> target, const std::string& key) { return target->GetPrivate( context, v8::Private::ForApi(context->GetIsolate(), gin::StringToV8(context->GetIsolate(), key))); } } // namespace v8::MaybeLocal<v8::Value> PassValueToOtherContext( v8::Local<v8::Context> source_context, v8::Local<v8::Context> destination_context, v8::Local<v8::Value> value, context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, int recursion_depth, BridgeErrorTarget error_target) { TRACE_EVENT0("electron", "ContextBridge::PassValueToOtherContext"); if (recursion_depth >= kMaxRecursion) { v8::Context::Scope error_scope(error_target == BridgeErrorTarget::kSource ? source_context : destination_context); source_context->GetIsolate()->ThrowException(v8::Exception::TypeError( gin::StringToV8(source_context->GetIsolate(), "Electron contextBridge recursion depth exceeded. " "Nested objects " "deeper than 1000 are not supported."))); return v8::MaybeLocal<v8::Value>(); } // Certain primitives always use the current contexts prototype and we can // pass these through directly which is significantly more performant than // copying them. This list of primitives is based on the classification of // "primitive value" as defined in the ECMA262 spec // https://tc39.es/ecma262/#sec-primitive-value if (value->IsString() || value->IsNumber() || value->IsNullOrUndefined() || value->IsBoolean() || value->IsSymbol() || value->IsBigInt()) { return v8::MaybeLocal<v8::Value>(value); } // Check Cache auto cached_value = object_cache->GetCachedProxiedObject(value); if (!cached_value.IsEmpty()) { return cached_value; } // Proxy functions and monitor the lifetime in the new context to release // the global handle at the right time. if (value->IsFunction()) { auto func = value.As<v8::Function>(); v8::MaybeLocal<v8::Value> maybe_original_fn = GetPrivate( source_context, func, context_bridge::kOriginalFunctionPrivateKey); { v8::Context::Scope destination_scope(destination_context); v8::Local<v8::Value> proxy_func; // If this function has already been sent over the bridge, // then it is being sent _back_ over the bridge and we can // simply return the original method here for performance reasons // For safety reasons we check if the destination context is the // creation context of the original method. If it's not we proceed // with the proxy logic if (maybe_original_fn.ToLocal(&proxy_func) && proxy_func->IsFunction() && proxy_func.As<v8::Object>()->GetCreationContextChecked() == destination_context) { return v8::MaybeLocal<v8::Value>(proxy_func); } v8::Local<v8::Object> state = v8::Object::New(destination_context->GetIsolate()); SetPrivate(destination_context, state, context_bridge::kProxyFunctionPrivateKey, func); SetPrivate(destination_context, state, context_bridge::kSupportsDynamicPropertiesPrivateKey, gin::ConvertToV8(destination_context->GetIsolate(), support_dynamic_properties)); if (!v8::Function::New(destination_context, ProxyFunctionWrapper, state) .ToLocal(&proxy_func)) return v8::MaybeLocal<v8::Value>(); SetPrivate(destination_context, proxy_func.As<v8::Object>(), context_bridge::kOriginalFunctionPrivateKey, func); object_cache->CacheProxiedObject(value, proxy_func); return v8::MaybeLocal<v8::Value>(proxy_func); } } // Proxy promises as they have a safe and guaranteed memory lifecycle if (value->IsPromise()) { v8::Context::Scope destination_scope(destination_context); auto source_promise = value.As<v8::Promise>(); // Make the promise a shared_ptr so that when the original promise is // freed the proxy promise is correctly freed as well instead of being // left dangling auto proxied_promise = std::make_shared<gin_helper::Promise<v8::Local<v8::Value>>>( destination_context->GetIsolate()); v8::Local<v8::Promise> proxied_promise_handle = proxied_promise->GetHandle(); v8::Global<v8::Context> global_then_source_context( source_context->GetIsolate(), source_context); v8::Global<v8::Context> global_then_destination_context( destination_context->GetIsolate(), destination_context); global_then_source_context.SetWeak(); global_then_destination_context.SetWeak(); auto then_cb = base::BindOnce( [](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> proxied_promise, v8::Isolate* isolate, v8::Global<v8::Context> global_source_context, v8::Global<v8::Context> global_destination_context, v8::Local<v8::Value> result) { if (global_source_context.IsEmpty() || global_destination_context.IsEmpty()) return; context_bridge::ObjectCache object_cache; auto val = PassValueToOtherContext(global_source_context.Get(isolate), global_destination_context.Get(isolate), result, &object_cache, false, 0); if (!val.IsEmpty()) proxied_promise->Resolve(val.ToLocalChecked()); }, proxied_promise, destination_context->GetIsolate(), std::move(global_then_source_context), std::move(global_then_destination_context)); v8::Global<v8::Context> global_catch_source_context( source_context->GetIsolate(), source_context); v8::Global<v8::Context> global_catch_destination_context( destination_context->GetIsolate(), destination_context); global_catch_source_context.SetWeak(); global_catch_destination_context.SetWeak(); auto catch_cb = base::BindOnce( [](std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> proxied_promise, v8::Isolate* isolate, v8::Global<v8::Context> global_source_context, v8::Global<v8::Context> global_destination_context, v8::Local<v8::Value> result) { if (global_source_context.IsEmpty() || global_destination_context.IsEmpty()) return; context_bridge::ObjectCache object_cache; auto val = PassValueToOtherContext(global_source_context.Get(isolate), global_destination_context.Get(isolate), result, &object_cache, false, 0); if (!val.IsEmpty()) proxied_promise->Reject(val.ToLocalChecked()); }, proxied_promise, destination_context->GetIsolate(), std::move(global_catch_source_context), std::move(global_catch_destination_context)); std::ignore = source_promise->Then( source_context, gin::ConvertToV8(destination_context->GetIsolate(), std::move(then_cb)) .As<v8::Function>(), gin::ConvertToV8(destination_context->GetIsolate(), std::move(catch_cb)) .As<v8::Function>()); object_cache->CacheProxiedObject(value, proxied_promise_handle); return v8::MaybeLocal<v8::Value>(proxied_promise_handle); } // Errors aren't serializable currently, we need to pull the message out and // re-construct in the destination context if (value->IsNativeError()) { v8::Context::Scope destination_context_scope(destination_context); // We should try to pull "message" straight off of the error as a // v8::Message includes some pretext that can get duplicated each time it // crosses the bridge we fallback to the v8::Message approach if we can't // pull "message" for some reason v8::MaybeLocal<v8::Value> maybe_message = value.As<v8::Object>()->Get( source_context, gin::ConvertToV8(source_context->GetIsolate(), "message")); v8::Local<v8::Value> message; if (maybe_message.ToLocal(&message) && message->IsString()) { return v8::MaybeLocal<v8::Value>( v8::Exception::Error(message.As<v8::String>())); } return v8::MaybeLocal<v8::Value>(v8::Exception::Error( v8::Exception::CreateMessage(destination_context->GetIsolate(), value) ->Get())); } // Manually go through the array and pass each value individually into a new // array so that functions deep inside arrays get proxied or arrays of // promises are proxied correctly. if (IsPlainArray(value)) { v8::Context::Scope destination_context_scope(destination_context); v8::Local<v8::Array> arr = value.As<v8::Array>(); size_t length = arr->Length(); v8::Local<v8::Array> cloned_arr = v8::Array::New(destination_context->GetIsolate(), length); for (size_t i = 0; i < length; i++) { auto value_for_array = PassValueToOtherContext( source_context, destination_context, arr->Get(source_context, i).ToLocalChecked(), object_cache, support_dynamic_properties, recursion_depth + 1); if (value_for_array.IsEmpty()) return v8::MaybeLocal<v8::Value>(); if (!IsTrue(cloned_arr->Set(destination_context, static_cast<int>(i), value_for_array.ToLocalChecked()))) { return v8::MaybeLocal<v8::Value>(); } } object_cache->CacheProxiedObject(value, cloned_arr); return v8::MaybeLocal<v8::Value>(cloned_arr); } // Custom logic to "clone" Element references blink::WebElement elem = blink::WebElement::FromV8Value(value); if (!elem.IsNull()) { v8::Context::Scope destination_context_scope(destination_context); return v8::MaybeLocal<v8::Value>(elem.ToV8Value( destination_context->Global(), destination_context->GetIsolate())); } // Custom logic to "clone" Blob references blink::WebBlob blob = blink::WebBlob::FromV8Value(value); if (!blob.IsNull()) { v8::Context::Scope destination_context_scope(destination_context); return v8::MaybeLocal<v8::Value>(blob.ToV8Value( destination_context->Global(), destination_context->GetIsolate())); } // Proxy all objects if (IsPlainObject(value)) { auto object_value = value.As<v8::Object>(); auto passed_value = CreateProxyForAPI( object_value, source_context, destination_context, object_cache, support_dynamic_properties, recursion_depth + 1); if (passed_value.IsEmpty()) return v8::MaybeLocal<v8::Value>(); return v8::MaybeLocal<v8::Value>(passed_value.ToLocalChecked()); } // Serializable objects blink::CloneableMessage ret; { v8::Local<v8::Context> error_context = error_target == BridgeErrorTarget::kSource ? source_context : destination_context; v8::Context::Scope error_scope(error_context); // V8 serializer will throw an error if required if (!gin::ConvertFromV8(error_context->GetIsolate(), value, &ret)) return v8::MaybeLocal<v8::Value>(); } { v8::Context::Scope destination_context_scope(destination_context); v8::Local<v8::Value> cloned_value = gin::ConvertToV8(destination_context->GetIsolate(), ret); object_cache->CacheProxiedObject(value, cloned_value); return v8::MaybeLocal<v8::Value>(cloned_value); } } void ProxyFunctionWrapper(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT0("electron", "ContextBridge::ProxyFunctionWrapper"); CHECK(info.Data()->IsObject()); v8::Local<v8::Object> data = info.Data().As<v8::Object>(); bool support_dynamic_properties = false; gin::Arguments args(info); // Context the proxy function was called from v8::Local<v8::Context> calling_context = args.isolate()->GetCurrentContext(); // Pull the original function and its context off of the data private key v8::MaybeLocal<v8::Value> sdp_value = GetPrivate(calling_context, data, context_bridge::kSupportsDynamicPropertiesPrivateKey); v8::MaybeLocal<v8::Value> maybe_func = GetPrivate( calling_context, data, context_bridge::kProxyFunctionPrivateKey); v8::Local<v8::Value> func_value; if (sdp_value.IsEmpty() || maybe_func.IsEmpty() || !gin::ConvertFromV8(args.isolate(), sdp_value.ToLocalChecked(), &support_dynamic_properties) || !maybe_func.ToLocal(&func_value)) return; v8::Local<v8::Function> func = func_value.As<v8::Function>(); v8::Local<v8::Context> func_owning_context = func->GetCreationContextChecked(); { v8::Context::Scope func_owning_context_scope(func_owning_context); context_bridge::ObjectCache object_cache; std::vector<v8::Local<v8::Value>> original_args; std::vector<v8::Local<v8::Value>> proxied_args; args.GetRemaining(&original_args); for (auto value : original_args) { auto arg = PassValueToOtherContext(calling_context, func_owning_context, value, &object_cache, support_dynamic_properties, 0); if (arg.IsEmpty()) return; proxied_args.push_back(arg.ToLocalChecked()); } v8::MaybeLocal<v8::Value> maybe_return_value; bool did_error = false; v8::Local<v8::Value> error_message; { v8::TryCatch try_catch(args.isolate()); maybe_return_value = func->Call(func_owning_context, func, proxied_args.size(), proxied_args.data()); if (try_catch.HasCaught()) { did_error = true; v8::Local<v8::Value> exception = try_catch.Exception(); const char err_msg[] = "An unknown exception occurred in the isolated context, an error " "occurred but a valid exception was not thrown."; if (!exception->IsNull() && exception->IsObject()) { v8::MaybeLocal<v8::Value> maybe_message = exception.As<v8::Object>()->Get( func_owning_context, gin::ConvertToV8(args.isolate(), "message")); if (!maybe_message.ToLocal(&error_message) || !error_message->IsString()) { error_message = gin::StringToV8(args.isolate(), err_msg); } } else { error_message = gin::StringToV8(args.isolate(), err_msg); } } } if (did_error) { v8::Context::Scope calling_context_scope(calling_context); args.isolate()->ThrowException( v8::Exception::Error(error_message.As<v8::String>())); return; } if (maybe_return_value.IsEmpty()) return; auto ret = PassValueToOtherContext( func_owning_context, calling_context, maybe_return_value.ToLocalChecked(), &object_cache, support_dynamic_properties, 0, BridgeErrorTarget::kDestination); if (ret.IsEmpty()) return; info.GetReturnValue().Set(ret.ToLocalChecked()); } } v8::MaybeLocal<v8::Object> CreateProxyForAPI( const v8::Local<v8::Object>& api_object, const v8::Local<v8::Context>& source_context, const v8::Local<v8::Context>& destination_context, context_bridge::ObjectCache* object_cache, bool support_dynamic_properties, int recursion_depth) { gin_helper::Dictionary api(source_context->GetIsolate(), api_object); { v8::Context::Scope destination_context_scope(destination_context); gin_helper::Dictionary proxy = gin::Dictionary::CreateEmpty(destination_context->GetIsolate()); object_cache->CacheProxiedObject(api.GetHandle(), proxy.GetHandle()); auto maybe_keys = api.GetHandle()->GetOwnPropertyNames( source_context, static_cast<v8::PropertyFilter>(v8::ONLY_ENUMERABLE)); if (maybe_keys.IsEmpty()) return v8::MaybeLocal<v8::Object>(proxy.GetHandle()); auto keys = maybe_keys.ToLocalChecked(); uint32_t length = keys->Length(); for (uint32_t i = 0; i < length; i++) { v8::Local<v8::Value> key = keys->Get(destination_context, i).ToLocalChecked(); if (support_dynamic_properties) { v8::Context::Scope source_context_scope(source_context); auto maybe_desc = api.GetHandle()->GetOwnPropertyDescriptor( source_context, key.As<v8::Name>()); v8::Local<v8::Value> desc_value; if (!maybe_desc.ToLocal(&desc_value) || !desc_value->IsObject()) continue; gin_helper::Dictionary desc(api.isolate(), desc_value.As<v8::Object>()); if (desc.Has("get") || desc.Has("set")) { v8::Local<v8::Value> getter; v8::Local<v8::Value> setter; desc.Get("get", &getter); desc.Get("set", &setter); { v8::Context::Scope inner_destination_context_scope( destination_context); v8::Local<v8::Value> getter_proxy; v8::Local<v8::Value> setter_proxy; if (!getter.IsEmpty()) { if (!PassValueToOtherContext(source_context, destination_context, getter, object_cache, support_dynamic_properties, 1) .ToLocal(&getter_proxy)) continue; } if (!setter.IsEmpty()) { if (!PassValueToOtherContext(source_context, destination_context, setter, object_cache, support_dynamic_properties, 1) .ToLocal(&setter_proxy)) continue; } v8::PropertyDescriptor prop_desc(getter_proxy, setter_proxy); std::ignore = proxy.GetHandle()->DefineProperty( destination_context, key.As<v8::Name>(), prop_desc); } continue; } } v8::Local<v8::Value> value; if (!api.Get(key, &value)) continue; auto passed_value = PassValueToOtherContext( source_context, destination_context, value, object_cache, support_dynamic_properties, recursion_depth + 1); if (passed_value.IsEmpty()) return v8::MaybeLocal<v8::Object>(); proxy.Set(key, passed_value.ToLocalChecked()); } return proxy.GetHandle(); } } void ExposeAPIInMainWorld(v8::Isolate* isolate, const std::string& key, v8::Local<v8::Value> api, gin_helper::Arguments* args) { TRACE_EVENT1("electron", "ContextBridge::ExposeAPIInMainWorld", "key", key); auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global()); CHECK(render_frame); auto* frame = render_frame->GetWebFrame(); CHECK(frame); v8::Local<v8::Context> main_context = frame->MainWorldScriptContext(); gin_helper::Dictionary global(main_context->GetIsolate(), main_context->Global()); if (global.Has(key)) { args->ThrowError( "Cannot bind an API on top of an existing property on the window " "object"); return; } v8::Local<v8::Context> isolated_context = frame->GetScriptContextFromWorldId( args->isolate(), WorldIDs::ISOLATED_WORLD_ID); { context_bridge::ObjectCache object_cache; v8::Context::Scope main_context_scope(main_context); v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( isolated_context, main_context, api, &object_cache, false, 0); if (maybe_proxy.IsEmpty()) return; auto proxy = maybe_proxy.ToLocalChecked(); if (base::FeatureList::IsEnabled(features::kContextBridgeMutability)) { global.Set(key, proxy); return; } if (proxy->IsObject() && !proxy->IsTypedArray() && !DeepFreeze(proxy.As<v8::Object>(), main_context)) return; global.SetReadOnlyNonConfigurable(key, proxy); } } gin_helper::Dictionary TraceKeyPath(const gin_helper::Dictionary& start, const std::vector<std::string>& key_path) { gin_helper::Dictionary current = start; for (size_t i = 0; i < key_path.size() - 1; i++) { CHECK(current.Get(key_path[i], &current)); } return current; } void OverrideGlobalValueFromIsolatedWorld( const std::vector<std::string>& key_path, v8::Local<v8::Object> value, bool support_dynamic_properties) { if (key_path.empty()) return; auto* render_frame = GetRenderFrame(value); CHECK(render_frame); auto* frame = render_frame->GetWebFrame(); CHECK(frame); v8::Local<v8::Context> main_context = frame->MainWorldScriptContext(); gin_helper::Dictionary global(main_context->GetIsolate(), main_context->Global()); const std::string final_key = key_path[key_path.size() - 1]; gin_helper::Dictionary target_object = TraceKeyPath(global, key_path); { v8::Context::Scope main_context_scope(main_context); context_bridge::ObjectCache object_cache; v8::MaybeLocal<v8::Value> maybe_proxy = PassValueToOtherContext( value->GetCreationContextChecked(), main_context, value, &object_cache, support_dynamic_properties, 1); DCHECK(!maybe_proxy.IsEmpty()); auto proxy = maybe_proxy.ToLocalChecked(); target_object.Set(final_key, proxy); } } bool OverrideGlobalPropertyFromIsolatedWorld( const std::vector<std::string>& key_path, v8::Local<v8::Object> getter, v8::Local<v8::Value> setter, gin_helper::Arguments* args) { if (key_path.empty()) return false; auto* render_frame = GetRenderFrame(getter); CHECK(render_frame); auto* frame = render_frame->GetWebFrame(); CHECK(frame); v8::Local<v8::Context> main_context = frame->MainWorldScriptContext(); gin_helper::Dictionary global(main_context->GetIsolate(), main_context->Global()); const std::string final_key = key_path[key_path.size() - 1]; v8::Local<v8::Object> target_object = TraceKeyPath(global, key_path).GetHandle(); { v8::Context::Scope main_context_scope(main_context); context_bridge::ObjectCache object_cache; v8::Local<v8::Value> getter_proxy; v8::Local<v8::Value> setter_proxy; if (!getter->IsNullOrUndefined()) { v8::MaybeLocal<v8::Value> maybe_getter_proxy = PassValueToOtherContext( getter->GetCreationContextChecked(), main_context, getter, &object_cache, false, 1); DCHECK(!maybe_getter_proxy.IsEmpty()); getter_proxy = maybe_getter_proxy.ToLocalChecked(); } if (!setter->IsNullOrUndefined() && setter->IsObject()) { v8::MaybeLocal<v8::Value> maybe_setter_proxy = PassValueToOtherContext( getter->GetCreationContextChecked(), main_context, setter, &object_cache, false, 1); DCHECK(!maybe_setter_proxy.IsEmpty()); setter_proxy = maybe_setter_proxy.ToLocalChecked(); } v8::PropertyDescriptor desc(getter_proxy, setter_proxy); bool success = IsTrue(target_object->DefineProperty( main_context, gin::StringToV8(args->isolate(), final_key), desc)); DCHECK(success); return success; } } bool IsCalledFromMainWorld(v8::Isolate* isolate) { auto* render_frame = GetRenderFrame(isolate->GetCurrentContext()->Global()); CHECK(render_frame); auto* frame = render_frame->GetWebFrame(); CHECK(frame); v8::Local<v8::Context> main_context = frame->MainWorldScriptContext(); return isolate->GetCurrentContext() == main_context; } } // namespace api } // namespace electron namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.SetMethod("exposeAPIInMainWorld", &electron::api::ExposeAPIInMainWorld); dict.SetMethod("_overrideGlobalValueFromIsolatedWorld", &electron::api::OverrideGlobalValueFromIsolatedWorld); dict.SetMethod("_overrideGlobalPropertyFromIsolatedWorld", &electron::api::OverrideGlobalPropertyFromIsolatedWorld); dict.SetMethod("_isCalledFromMainWorld", &electron::api::IsCalledFromMainWorld); #if DCHECK_IS_ON() dict.Set("_isDebug", true); #endif } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_renderer_context_bridge, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,588
[Feature Request]: `contextBridge.exposeInIsolatedWorld`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description I am working on application's plugin/add-on system and I want to disallow from plugins/add-ons doing anything without user giving permissions to them. This can work great with isolated worlds, but isolated worlds still lack things. Node's `vm` feels more powerful than Electron's isolated worlds, but Node's `vm` doesn't work great with Electron. You can't really set isolated world's window variables either without using hacks like executing JS in isolated world to set its window variables, which will make you struggle implementing functions properly. ### Proposed Solution The introduction of `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)`. This would allow you to set isolated world's window properties and would be similar to `contextBridge.exposeInMainWorld(apiKey, api)`. Example: ```js webFrame.setIsolatedWorldInfo(1005, { name: "Isolated World 5" }); contextBridge.exposeInIsolatedWorld(1005, "api", { doStuff() { console.log("Isolated World 5 is doing stuff"); } }); await webFrame.executeJavaScriptInIsolatedWorld(1005, [ { "code": "window.api.doStuff()" } ]); ``` Console Output: ``` -> Isolated World 5 is doing stuff ``` ### Alternatives Considered `webFrame.setIsolatedWorldInfo` could allow setting window variables for that isolated world. ### Additional Information _No response_
https://github.com/electron/electron/issues/32588
https://github.com/electron/electron/pull/34974
8c3c0f0b50634bd62c1a4c9a826d8c7aad329c11
dfc134de4286307e61d61f8b6c9ac6a984aed50f
2022-01-23T18:49:51Z
c++
2022-09-21T18:17:10Z
spec/api-context-bridge-spec.ts
import { BrowserWindow, ipcMain } from 'electron/main'; import { contextBridge } from 'electron/renderer'; import { expect } from 'chai'; import * as fs from 'fs-extra'; import * as http from 'http'; import * as os from 'os'; import * as path from 'path'; import * as cp from 'child_process'; import { closeWindow } from './window-helpers'; import { emittedOnce } from './events-helpers'; import { AddressInfo } from 'net'; const fixturesPath = path.resolve(__dirname, 'fixtures', 'api', 'context-bridge'); describe('contextBridge', () => { let w: BrowserWindow; let dir: string; let server: http.Server; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); }); after(async () => { if (server) await new Promise(resolve => server.close(resolve)); server = null as any; }); afterEach(async () => { await closeWindow(w); if (dir) await fs.remove(dir); }); it('should not be accessible when contextIsolation is disabled', async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false, preload: path.resolve(fixturesPath, 'can-bind-preload.js') } }); const [, bound] = await emittedOnce(ipcMain, 'context-bridge-bound', () => w.loadFile(path.resolve(fixturesPath, 'empty.html'))); expect(bound).to.equal(false); }); it('should be accessible when contextIsolation is enabled', async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.resolve(fixturesPath, 'can-bind-preload.js') } }); const [, bound] = await emittedOnce(ipcMain, 'context-bridge-bound', () => w.loadFile(path.resolve(fixturesPath, 'empty.html'))); expect(bound).to.equal(true); }); const generateTests = (useSandbox: boolean) => { describe(`with sandbox=${useSandbox}`, () => { const makeBindingWindow = async (bindingCreator: Function) => { const preloadContent = `const renderer_1 = require('electron'); ${useSandbox ? '' : `require('v8').setFlagsFromString('--expose_gc'); const gc=require('vm').runInNewContext('gc'); renderer_1.contextBridge.exposeInMainWorld('GCRunner', { run: () => gc() });`} (${bindingCreator.toString()})();`; const tmpDir = await fs.mkdtemp(path.resolve(os.tmpdir(), 'electron-spec-preload-')); dir = tmpDir; await fs.writeFile(path.resolve(tmpDir, 'preload.js'), preloadContent); w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, nodeIntegration: true, sandbox: useSandbox, preload: path.resolve(tmpDir, 'preload.js'), additionalArguments: ['--unsafely-expose-electron-internals-for-testing'] } }); await w.loadURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`); }; const callWithBindings = (fn: Function) => w.webContents.executeJavaScript(`(${fn.toString()})(window)`); const getGCInfo = async (): Promise<{ trackedValues: number; }> => { const [, info] = await emittedOnce(ipcMain, 'gc-info', () => w.webContents.send('get-gc-info')); return info; }; const forceGCOnWindow = async () => { w.webContents.debugger.attach(); await w.webContents.debugger.sendCommand('HeapProfiler.enable'); await w.webContents.debugger.sendCommand('HeapProfiler.collectGarbage'); await w.webContents.debugger.sendCommand('HeapProfiler.disable'); w.webContents.debugger.detach(); }; it('should proxy numbers', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', 123); }); const result = await callWithBindings((root: any) => { return root.example; }); expect(result).to.equal(123); }); it('should make global properties read-only', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', 123); }); const result = await callWithBindings((root: any) => { root.example = 456; return root.example; }); expect(result).to.equal(123); }); it('should proxy nested numbers', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myNumber: 123 }); }); const result = await callWithBindings((root: any) => { return root.example.myNumber; }); expect(result).to.equal(123); }); it('should make properties unwriteable', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myNumber: 123 }); }); const result = await callWithBindings((root: any) => { root.example.myNumber = 456; return root.example.myNumber; }); expect(result).to.equal(123); }); it('should proxy strings', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', 'my-words'); }); const result = await callWithBindings((root: any) => { return root.example; }); expect(result).to.equal('my-words'); }); it('should proxy nested strings', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myString: 'my-words' }); }); const result = await callWithBindings((root: any) => { return root.example.myString; }); expect(result).to.equal('my-words'); }); it('should proxy arrays', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', [123, 'my-words']); }); const result = await callWithBindings((root: any) => { return [root.example, Array.isArray(root.example)]; }); expect(result).to.deep.equal([[123, 'my-words'], true]); }); it('should proxy nested arrays', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myArr: [123, 'my-words'] }); }); const result = await callWithBindings((root: any) => { return root.example.myArr; }); expect(result).to.deep.equal([123, 'my-words']); }); it('should make arrays immutable', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', [123, 'my-words']); }); const immutable = await callWithBindings((root: any) => { try { root.example.push(456); return false; } catch { return true; } }); expect(immutable).to.equal(true); }); it('should make nested arrays immutable', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myArr: [123, 'my-words'] }); }); const immutable = await callWithBindings((root: any) => { try { root.example.myArr.push(456); return false; } catch { return true; } }); expect(immutable).to.equal(true); }); it('should proxy booleans', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', true); }); const result = await callWithBindings((root: any) => { return root.example; }); expect(result).to.equal(true); }); it('should proxy nested booleans', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myBool: true }); }); const result = await callWithBindings((root: any) => { return root.example.myBool; }); expect(result).to.equal(true); }); it('should proxy promises and resolve with the correct value', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', Promise.resolve('i-resolved') ); }); const result = await callWithBindings((root: any) => { return root.example; }); expect(result).to.equal('i-resolved'); }); it('should proxy nested promises and resolve with the correct value', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myPromise: Promise.resolve('i-resolved') }); }); const result = await callWithBindings((root: any) => { return root.example.myPromise; }); expect(result).to.equal('i-resolved'); }); it('should proxy promises and reject with the correct value', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', Promise.reject(new Error('i-rejected'))); }); const result = await callWithBindings(async (root: any) => { try { await root.example; return null; } catch (err) { return err; } }); expect(result).to.be.an.instanceOf(Error).with.property('message', 'i-rejected'); }); it('should proxy nested promises and reject with the correct value', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myPromise: Promise.reject(new Error('i-rejected')) }); }); const result = await callWithBindings(async (root: any) => { try { await root.example.myPromise; return null; } catch (err) { return err; } }); expect(result).to.be.an.instanceOf(Error).with.property('message', 'i-rejected'); }); it('should proxy promises and resolve with the correct value if it resolves later', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myPromise: () => new Promise(resolve => setTimeout(() => resolve('delayed'), 20)) }); }); const result = await callWithBindings((root: any) => { return root.example.myPromise(); }); expect(result).to.equal('delayed'); }); it('should proxy nested promises correctly', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { myPromise: () => new Promise(resolve => setTimeout(() => resolve(Promise.resolve(123)), 20)) }); }); const result = await callWithBindings((root: any) => { return root.example.myPromise(); }); expect(result).to.equal(123); }); it('should proxy methods', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getNumber: () => 123, getString: () => 'help', getBoolean: () => false, getPromise: async () => 'promise' }); }); const result = await callWithBindings(async (root: any) => { return [root.example.getNumber(), root.example.getString(), root.example.getBoolean(), await root.example.getPromise()]; }); expect(result).to.deep.equal([123, 'help', false, 'promise']); }); it('should proxy functions', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', () => 'return-value'); }); const result = await callWithBindings(async (root: any) => { return root.example(); }); expect(result).equal('return-value'); }); it('should not double-proxy functions when they are returned to their origin side of the bridge', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', (fn: any) => fn); }); const result = await callWithBindings(async (root: any) => { const fn = () => null; return root.example(fn) === fn; }); expect(result).equal(true); }); it('should properly handle errors thrown in proxied functions', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', () => { throw new Error('oh no'); }); }); const result = await callWithBindings(async (root: any) => { try { root.example(); } catch (e) { return (e as Error).message; } }); expect(result).equal('oh no'); }); it('should proxy methods that are callable multiple times', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { doThing: () => 123 }); }); const result = await callWithBindings(async (root: any) => { return [root.example.doThing(), root.example.doThing(), root.example.doThing()]; }); expect(result).to.deep.equal([123, 123, 123]); }); it('should proxy methods in the reverse direction', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { callWithNumber: (fn: any) => fn(123) }); }); const result = await callWithBindings(async (root: any) => { return root.example.callWithNumber((n: number) => n + 1); }); expect(result).to.equal(124); }); it('should proxy promises in the reverse direction', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getPromiseValue: (p: Promise<any>) => p }); }); const result = await callWithBindings((root: any) => { return root.example.getPromiseValue(Promise.resolve('my-proxied-value')); }); expect(result).to.equal('my-proxied-value'); }); it('should proxy objects with number keys', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { 1: 123, 2: 456, 3: 789 }); }); const result = await callWithBindings(async (root: any) => { return [root.example[1], root.example[2], root.example[3], Array.isArray(root.example)]; }); expect(result).to.deep.equal([123, 456, 789, false]); }); it('it should proxy null', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', null); }); const result = await callWithBindings((root: any) => { // Convert to strings as although the context bridge keeps the right value // IPC does not return `${root.example}`; }); expect(result).to.deep.equal('null'); }); it('it should proxy undefined', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', undefined); }); const result = await callWithBindings((root: any) => { // Convert to strings as although the context bridge keeps the right value // IPC does not return `${root.example}`; }); expect(result).to.deep.equal('undefined'); }); it('it should proxy nested null and undefined correctly', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { values: [null, undefined] }); }); const result = await callWithBindings((root: any) => { // Convert to strings as although the context bridge keeps the right value // IPC does not return root.example.values.map((val: any) => `${val}`); }); expect(result).to.deep.equal(['null', 'undefined']); }); it('should proxy symbols', async () => { await makeBindingWindow(() => { const mySymbol = Symbol('unique'); const isSymbol = (s: Symbol) => s === mySymbol; contextBridge.exposeInMainWorld('symbol', mySymbol); contextBridge.exposeInMainWorld('isSymbol', isSymbol); }); const result = await callWithBindings((root: any) => { return root.isSymbol(root.symbol); }); expect(result).to.equal(true, 'symbols should be equal across contexts'); }); it('should proxy symbols such that symbol equality works', async () => { await makeBindingWindow(() => { const mySymbol = Symbol('unique'); contextBridge.exposeInMainWorld('example', { getSymbol: () => mySymbol, isSymbol: (s: Symbol) => s === mySymbol }); }); const result = await callWithBindings((root: any) => { return root.example.isSymbol(root.example.getSymbol()); }); expect(result).to.equal(true, 'symbols should be equal across contexts'); }); it('should proxy symbols such that symbol key lookup works', async () => { await makeBindingWindow(() => { const mySymbol = Symbol('unique'); contextBridge.exposeInMainWorld('example', { getSymbol: () => mySymbol, getObject: () => ({ [mySymbol]: 123 }) }); }); const result = await callWithBindings((root: any) => { return root.example.getObject()[root.example.getSymbol()]; }); expect(result).to.equal(123, 'symbols key lookup should work across contexts'); }); it('should proxy typed arrays', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', new Uint8Array(100)); }); const result = await callWithBindings((root: any) => { return Object.getPrototypeOf(root.example) === Uint8Array.prototype; }); expect(result).equal(true); }); it('should proxy regexps', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', /a/g); }); const result = await callWithBindings((root: any) => { return Object.getPrototypeOf(root.example) === RegExp.prototype; }); expect(result).equal(true); }); it('should proxy typed arrays and regexps through the serializer', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { arr: new Uint8Array(100), regexp: /a/g }); }); const result = await callWithBindings((root: any) => { return [ Object.getPrototypeOf(root.example.arr) === Uint8Array.prototype, Object.getPrototypeOf(root.example.regexp) === RegExp.prototype ]; }); expect(result).to.deep.equal([true, true]); }); it('should handle recursive objects', async () => { await makeBindingWindow(() => { const o: any = { value: 135 }; o.o = o; contextBridge.exposeInMainWorld('example', { o }); }); const result = await callWithBindings((root: any) => { return [root.example.o.value, root.example.o.o.value, root.example.o.o.o.value]; }); expect(result).to.deep.equal([135, 135, 135]); }); it('should handle DOM elements', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getElem: () => document.body }); }); const result = await callWithBindings((root: any) => { return [root.example.getElem().tagName, root.example.getElem().constructor.name, typeof root.example.getElem().querySelector]; }); expect(result).to.deep.equal(['BODY', 'HTMLBodyElement', 'function']); }); it('should handle DOM elements going backwards over the bridge', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getElemInfo: (fn: Function) => { const elem = fn(); return [elem.tagName, elem.constructor.name, typeof elem.querySelector]; } }); }); const result = await callWithBindings((root: any) => { return root.example.getElemInfo(() => document.body); }); expect(result).to.deep.equal(['BODY', 'HTMLBodyElement', 'function']); }); it('should handle Blobs', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getBlob: () => new Blob(['ab', 'cd']) }); }); const result = await callWithBindings(async (root: any) => { return [await root.example.getBlob().text()]; }); expect(result).to.deep.equal(['abcd']); }); it('should handle Blobs going backwards over the bridge', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { getBlobText: async (fn: Function) => { const blob = fn(); return [await blob.text()]; } }); }); const result = await callWithBindings((root: any) => { return root.example.getBlobText(() => new Blob(['12', '45'])); }); expect(result).to.deep.equal(['1245']); }); // Can only run tests which use the GCRunner in non-sandboxed environments if (!useSandbox) { it('should release the global hold on methods sent across contexts', async () => { await makeBindingWindow(() => { const trackedValues: WeakRef<object>[] = []; require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', { trackedValues: trackedValues.filter(value => value.deref()).length })); contextBridge.exposeInMainWorld('example', { getFunction: () => () => 123, track: (value: object) => { trackedValues.push(new WeakRef(value)); } }); }); await callWithBindings(async (root: any) => { root.GCRunner.run(); }); expect((await getGCInfo()).trackedValues).to.equal(0); await callWithBindings(async (root: any) => { const fn = root.example.getFunction(); root.example.track(fn); root.x = [fn]; }); expect((await getGCInfo()).trackedValues).to.equal(1); await callWithBindings(async (root: any) => { root.x = []; root.GCRunner.run(); }); expect((await getGCInfo()).trackedValues).to.equal(0); }); } if (useSandbox) { it('should not leak the global hold on methods sent across contexts when reloading a sandboxed renderer', async () => { await makeBindingWindow(() => { const trackedValues: WeakRef<object>[] = []; require('electron').ipcRenderer.on('get-gc-info', e => e.sender.send('gc-info', { trackedValues: trackedValues.filter(value => value.deref()).length })); contextBridge.exposeInMainWorld('example', { getFunction: () => () => 123, track: (value: object) => { trackedValues.push(new WeakRef(value)); } }); require('electron').ipcRenderer.send('window-ready-for-tasking'); }); const loadPromise = emittedOnce(ipcMain, 'window-ready-for-tasking'); expect((await getGCInfo()).trackedValues).to.equal(0); await callWithBindings((root: any) => { root.example.track(root.example.getFunction()); }); expect((await getGCInfo()).trackedValues).to.equal(1); await callWithBindings((root: any) => { root.location.reload(); }); await loadPromise; await forceGCOnWindow(); // If this is ever "2" it means we leaked the exposed function and // therefore the entire context after a reload expect((await getGCInfo()).trackedValues).to.equal(0); }); } it('it should not let you overwrite existing exposed things', async () => { await makeBindingWindow(() => { let threw = false; contextBridge.exposeInMainWorld('example', { attempt: 1, getThrew: () => threw }); try { contextBridge.exposeInMainWorld('example', { attempt: 2, getThrew: () => threw }); } catch { threw = true; } }); const result = await callWithBindings((root: any) => { return [root.example.attempt, root.example.getThrew()]; }); expect(result).to.deep.equal([1, true]); }); it('should work with complex nested methods and promises', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { first: (second: Function) => second((fourth: Function) => { return fourth(); }) }); }); const result = await callWithBindings((root: any) => { return root.example.first((third: Function) => { return third(() => Promise.resolve('final value')); }); }); expect(result).to.equal('final value'); }); it('should work with complex nested methods and promises attached directly to the global', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', (second: Function) => second((fourth: Function) => { return fourth(); }) ); }); const result = await callWithBindings((root: any) => { return root.example((third: Function) => { return third(() => Promise.resolve('final value')); }); }); expect(result).to.equal('final value'); }); it('should throw an error when recursion depth is exceeded', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { doThing: (a: any) => console.log(a) }); }); let threw = await callWithBindings((root: any) => { try { let a: any = []; for (let i = 0; i < 999; i++) { a = [a]; } root.example.doThing(a); return false; } catch { return true; } }); expect(threw).to.equal(false); threw = await callWithBindings((root: any) => { try { let a: any = []; for (let i = 0; i < 1000; i++) { a = [a]; } root.example.doThing(a); return false; } catch { return true; } }); expect(threw).to.equal(true); }); it('should copy thrown errors into the other context', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { throwNormal: () => { throw new Error('whoops'); }, throwWeird: () => { throw 'this is no error...'; // eslint-disable-line no-throw-literal }, throwNotClonable: () => { return Object(Symbol('foo')); }, argumentConvert: () => {} }); }); const result = await callWithBindings((root: any) => { const getError = (fn: Function) => { try { fn(); } catch (e) { return e; } return null; }; const normalIsError = Object.getPrototypeOf(getError(root.example.throwNormal)) === Error.prototype; const weirdIsError = Object.getPrototypeOf(getError(root.example.throwWeird)) === Error.prototype; const notClonableIsError = Object.getPrototypeOf(getError(root.example.throwNotClonable)) === Error.prototype; const argumentConvertIsError = Object.getPrototypeOf(getError(() => root.example.argumentConvert(Object(Symbol('test'))))) === Error.prototype; return [normalIsError, weirdIsError, notClonableIsError, argumentConvertIsError]; }); expect(result).to.deep.equal([true, true, true, true], 'should all be errors in the current context'); }); it('should not leak prototypes', async () => { await makeBindingWindow(() => { contextBridge.exposeInMainWorld('example', { number: 123, string: 'string', boolean: true, arr: [123, 'string', true, ['foo']], symbol: Symbol('foo'), bigInt: 10n, getObject: () => ({ thing: 123 }), getNumber: () => 123, getString: () => 'string', getBoolean: () => true, getArr: () => [123, 'string', true, ['foo']], getPromise: async () => ({ number: 123, string: 'string', boolean: true, fn: () => 'string', arr: [123, 'string', true, ['foo']] }), getFunctionFromFunction: async () => () => null, object: { number: 123, string: 'string', boolean: true, arr: [123, 'string', true, ['foo']], getPromise: async () => ({ number: 123, string: 'string', boolean: true, fn: () => 'string', arr: [123, 'string', true, ['foo']] }) }, receiveArguments: (fn: any) => fn({ key: 'value' }), symbolKeyed: { [Symbol('foo')]: 123 }, getBody: () => document.body, getBlob: () => new Blob(['ab', 'cd']) }); }); const result = await callWithBindings(async (root: any) => { const { example } = root; let arg: any; example.receiveArguments((o: any) => { arg = o; }); const protoChecks = [ ...Object.keys(example).map(key => [key, String]), ...Object.getOwnPropertySymbols(example.symbolKeyed).map(key => [key, Symbol]), [example, Object], [example.number, Number], [example.string, String], [example.boolean, Boolean], [example.arr, Array], [example.arr[0], Number], [example.arr[1], String], [example.arr[2], Boolean], [example.arr[3], Array], [example.arr[3][0], String], [example.symbol, Symbol], [example.bigInt, BigInt], [example.getNumber, Function], [example.getNumber(), Number], [example.getObject(), Object], [example.getString(), String], [example.getBoolean(), Boolean], [example.getArr(), Array], [example.getArr()[0], Number], [example.getArr()[1], String], [example.getArr()[2], Boolean], [example.getArr()[3], Array], [example.getArr()[3][0], String], [example.getFunctionFromFunction, Function], [example.getFunctionFromFunction(), Promise], [await example.getFunctionFromFunction(), Function], [example.getPromise(), Promise], [await example.getPromise(), Object], [(await example.getPromise()).number, Number], [(await example.getPromise()).string, String], [(await example.getPromise()).boolean, Boolean], [(await example.getPromise()).fn, Function], [(await example.getPromise()).fn(), String], [(await example.getPromise()).arr, Array], [(await example.getPromise()).arr[0], Number], [(await example.getPromise()).arr[1], String], [(await example.getPromise()).arr[2], Boolean], [(await example.getPromise()).arr[3], Array], [(await example.getPromise()).arr[3][0], String], [example.object, Object], [example.object.number, Number], [example.object.string, String], [example.object.boolean, Boolean], [example.object.arr, Array], [example.object.arr[0], Number], [example.object.arr[1], String], [example.object.arr[2], Boolean], [example.object.arr[3], Array], [example.object.arr[3][0], String], [await example.object.getPromise(), Object], [(await example.object.getPromise()).number, Number], [(await example.object.getPromise()).string, String], [(await example.object.getPromise()).boolean, Boolean], [(await example.object.getPromise()).fn, Function], [(await example.object.getPromise()).fn(), String], [(await example.object.getPromise()).arr, Array], [(await example.object.getPromise()).arr[0], Number], [(await example.object.getPromise()).arr[1], String], [(await example.object.getPromise()).arr[2], Boolean], [(await example.object.getPromise()).arr[3], Array], [(await example.object.getPromise()).arr[3][0], String], [arg, Object], [arg.key, String], [example.getBody(), HTMLBodyElement], [example.getBlob(), Blob] ]; return { protoMatches: protoChecks.map(([a, Constructor]) => Object.getPrototypeOf(a) === Constructor.prototype) }; }); // Every protomatch should be true expect(result.protoMatches).to.deep.equal(result.protoMatches.map(() => true)); }); it('should not leak prototypes when attaching directly to the global', async () => { await makeBindingWindow(() => { const toExpose = { number: 123, string: 'string', boolean: true, arr: [123, 'string', true, ['foo']], symbol: Symbol('foo'), bigInt: 10n, getObject: () => ({ thing: 123 }), getNumber: () => 123, getString: () => 'string', getBoolean: () => true, getArr: () => [123, 'string', true, ['foo']], getPromise: async () => ({ number: 123, string: 'string', boolean: true, fn: () => 'string', arr: [123, 'string', true, ['foo']] }), getFunctionFromFunction: async () => () => null, getError: () => new Error('foo'), getWeirdError: () => { const e = new Error('foo'); e.message = { garbage: true } as any; return e; }, object: { number: 123, string: 'string', boolean: true, arr: [123, 'string', true, ['foo']], getPromise: async () => ({ number: 123, string: 'string', boolean: true, fn: () => 'string', arr: [123, 'string', true, ['foo']] }) }, receiveArguments: (fn: any) => fn({ key: 'value' }), symbolKeyed: { [Symbol('foo')]: 123 } }; const keys: string[] = []; Object.entries(toExpose).forEach(([key, value]) => { keys.push(key); contextBridge.exposeInMainWorld(key, value); }); contextBridge.exposeInMainWorld('keys', keys); }); const result = await callWithBindings(async (root: any) => { const { keys } = root; const cleanedRoot: any = {}; for (const [key, value] of Object.entries(root)) { if (keys.includes(key)) { cleanedRoot[key] = value; } } let arg: any; cleanedRoot.receiveArguments((o: any) => { arg = o; }); const protoChecks = [ ...Object.keys(cleanedRoot).map(key => [key, String]), ...Object.getOwnPropertySymbols(cleanedRoot.symbolKeyed).map(key => [key, Symbol]), [cleanedRoot, Object], [cleanedRoot.number, Number], [cleanedRoot.string, String], [cleanedRoot.boolean, Boolean], [cleanedRoot.arr, Array], [cleanedRoot.arr[0], Number], [cleanedRoot.arr[1], String], [cleanedRoot.arr[2], Boolean], [cleanedRoot.arr[3], Array], [cleanedRoot.arr[3][0], String], [cleanedRoot.symbol, Symbol], [cleanedRoot.bigInt, BigInt], [cleanedRoot.getNumber, Function], [cleanedRoot.getNumber(), Number], [cleanedRoot.getObject(), Object], [cleanedRoot.getString(), String], [cleanedRoot.getBoolean(), Boolean], [cleanedRoot.getArr(), Array], [cleanedRoot.getArr()[0], Number], [cleanedRoot.getArr()[1], String], [cleanedRoot.getArr()[2], Boolean], [cleanedRoot.getArr()[3], Array], [cleanedRoot.getArr()[3][0], String], [cleanedRoot.getFunctionFromFunction, Function], [cleanedRoot.getFunctionFromFunction(), Promise], [await cleanedRoot.getFunctionFromFunction(), Function], [cleanedRoot.getError(), Error], [cleanedRoot.getError().message, String], [cleanedRoot.getWeirdError(), Error], [cleanedRoot.getWeirdError().message, String], [cleanedRoot.getPromise(), Promise], [await cleanedRoot.getPromise(), Object], [(await cleanedRoot.getPromise()).number, Number], [(await cleanedRoot.getPromise()).string, String], [(await cleanedRoot.getPromise()).boolean, Boolean], [(await cleanedRoot.getPromise()).fn, Function], [(await cleanedRoot.getPromise()).fn(), String], [(await cleanedRoot.getPromise()).arr, Array], [(await cleanedRoot.getPromise()).arr[0], Number], [(await cleanedRoot.getPromise()).arr[1], String], [(await cleanedRoot.getPromise()).arr[2], Boolean], [(await cleanedRoot.getPromise()).arr[3], Array], [(await cleanedRoot.getPromise()).arr[3][0], String], [cleanedRoot.object, Object], [cleanedRoot.object.number, Number], [cleanedRoot.object.string, String], [cleanedRoot.object.boolean, Boolean], [cleanedRoot.object.arr, Array], [cleanedRoot.object.arr[0], Number], [cleanedRoot.object.arr[1], String], [cleanedRoot.object.arr[2], Boolean], [cleanedRoot.object.arr[3], Array], [cleanedRoot.object.arr[3][0], String], [await cleanedRoot.object.getPromise(), Object], [(await cleanedRoot.object.getPromise()).number, Number], [(await cleanedRoot.object.getPromise()).string, String], [(await cleanedRoot.object.getPromise()).boolean, Boolean], [(await cleanedRoot.object.getPromise()).fn, Function], [(await cleanedRoot.object.getPromise()).fn(), String], [(await cleanedRoot.object.getPromise()).arr, Array], [(await cleanedRoot.object.getPromise()).arr[0], Number], [(await cleanedRoot.object.getPromise()).arr[1], String], [(await cleanedRoot.object.getPromise()).arr[2], Boolean], [(await cleanedRoot.object.getPromise()).arr[3], Array], [(await cleanedRoot.object.getPromise()).arr[3][0], String], [arg, Object], [arg.key, String] ]; return { protoMatches: protoChecks.map(([a, Constructor]) => Object.getPrototypeOf(a) === Constructor.prototype) }; }); // Every protomatch should be true expect(result.protoMatches).to.deep.equal(result.protoMatches.map(() => true)); }); describe('internalContextBridge', () => { describe('overrideGlobalValueFromIsolatedWorld', () => { it('should override top level properties', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueFromIsolatedWorld(['open'], () => ({ you: 'are a wizard' })); }); const result = await callWithBindings(async (root: any) => { return root.open(); }); expect(result).to.deep.equal({ you: 'are a wizard' }); }); it('should override deep properties', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueFromIsolatedWorld(['document', 'foo'], () => 'I am foo'); }); const result = await callWithBindings(async (root: any) => { return root.document.foo(); }); expect(result).to.equal('I am foo'); }); }); describe('overrideGlobalPropertyFromIsolatedWorld', () => { it('should call the getter correctly', async () => { await makeBindingWindow(() => { let callCount = 0; const getter = () => { callCount++; return true; }; contextBridge.internalContextBridge!.overrideGlobalPropertyFromIsolatedWorld(['isFun'], getter); contextBridge.exposeInMainWorld('foo', { callCount: () => callCount }); }); const result = await callWithBindings(async (root: any) => { return [root.isFun, root.foo.callCount()]; }); expect(result[0]).to.equal(true); expect(result[1]).to.equal(1); }); it('should not make a setter if none is provided', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalPropertyFromIsolatedWorld(['isFun'], () => true); }); const result = await callWithBindings(async (root: any) => { root.isFun = 123; return root.isFun; }); expect(result).to.equal(true); }); it('should call the setter correctly', async () => { await makeBindingWindow(() => { const callArgs: any[] = []; const setter = (...args: any[]) => { callArgs.push(args); return true; }; contextBridge.internalContextBridge!.overrideGlobalPropertyFromIsolatedWorld(['isFun'], () => true, setter); contextBridge.exposeInMainWorld('foo', { callArgs: () => callArgs }); }); const result = await callWithBindings(async (root: any) => { root.isFun = 123; return root.foo.callArgs(); }); expect(result).to.have.lengthOf(1); expect(result[0]).to.have.lengthOf(1); expect(result[0][0]).to.equal(123); }); }); describe('overrideGlobalValueWithDynamicPropsFromIsolatedWorld', () => { it('should not affect normal values', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { a: 123, b: () => 2, c: () => ({ d: 3 }) }); }); const result = await callWithBindings(async (root: any) => { return [root.thing.a, root.thing.b(), root.thing.c()]; }); expect(result).to.deep.equal([123, 2, { d: 3 }]); }); it('should work with getters', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { get foo () { return 'hi there'; } }); }); const result = await callWithBindings(async (root: any) => { return root.thing.foo; }); expect(result).to.equal('hi there'); }); it('should work with nested getters', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { get foo () { return { get bar () { return 'hi there'; } }; } }); }); const result = await callWithBindings(async (root: any) => { return root.thing.foo.bar; }); expect(result).to.equal('hi there'); }); it('should work with setters', async () => { await makeBindingWindow(() => { let a: any = null; contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { get foo () { return a; }, set foo (arg: any) { a = arg + 1; } }); }); const result = await callWithBindings(async (root: any) => { root.thing.foo = 123; return root.thing.foo; }); expect(result).to.equal(124); }); it('should work with nested getter / setter combos', async () => { await makeBindingWindow(() => { let a: any = null; contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { get thingy () { return { get foo () { return a; }, set foo (arg: any) { a = arg + 1; } }; } }); }); const result = await callWithBindings(async (root: any) => { root.thing.thingy.foo = 123; return root.thing.thingy.foo; }); expect(result).to.equal(124); }); it('should work with deep properties', async () => { await makeBindingWindow(() => { contextBridge.internalContextBridge!.overrideGlobalValueWithDynamicPropsFromIsolatedWorld(['thing'], { a: () => ({ get foo () { return 'still here'; } }) }); }); const result = await callWithBindings(async (root: any) => { return root.thing.a().foo; }); expect(result).to.equal('still here'); }); }); }); }); }; generateTests(true); generateTests(false); }); describe('ContextBridgeMutability', () => { it('should not make properties unwriteable and read-only if ContextBridgeMutability is on', async () => { const appPath = path.join(fixturesPath, 'context-bridge-mutability'); const appProcess = cp.spawn(process.execPath, ['--enable-logging', '--enable-features=ContextBridgeMutability', appPath]); let output = ''; appProcess.stdout.on('data', data => { output += data; }); await emittedOnce(appProcess, 'exit'); expect(output).to.include('some-modified-text'); expect(output).to.include('obj-modified-prop'); expect(output).to.include('1,2,5,3,4'); }); it('should make properties unwriteable and read-only if ContextBridgeMutability is off', async () => { const appPath = path.join(fixturesPath, 'context-bridge-mutability'); const appProcess = cp.spawn(process.execPath, ['--enable-logging', appPath]); let output = ''; appProcess.stdout.on('data', data => { output += data; }); await emittedOnce(appProcess, 'exit'); expect(output).to.include('some-text'); expect(output).to.include('obj-prop'); expect(output).to.include('1,2,3,4'); }); });