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
37,419
[Bug]: Electron will crash when I call BrowserView.destroy().
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 21.4.2 ### Expected Behavior Electron will not exit and browserView will close. ### Actual Behavior Electron exited with code 3221225477. ### Testcase Gist URL _No response_ ### Additional Information I publish fiddle to github failed. /(ㄒoㄒ)/~~ main.js ``` // Modules to control application life and create native browser window const { app, BrowserWindow, BrowserView, ipcMain, dialog } = require('electron') const path = require('path') function createWindow() { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html') const mainView = new BrowserView({ webPreferences: { nodeIntegration: false, contextIsolation: true, } }) mainView.webContents.loadURL('https://boardmix.cn/app/') mainWindow.setBrowserView(mainView); const windowBounds = mainWindow.getContentBounds(); const viewWidth = windowBounds.width - 2; const viewHeight = windowBounds.height - 200 - 1; mainView.setBounds({ x: 1, y: 200, width: viewWidth, height: viewHeight }); ipcMain.on('close', () => { if (!mainView.webContents || mainView.webContents.isDestroyed()) { dialog.showMessageBox({message: 'webContents is destroyed'}) } else { mainView.webContents.destroy(); } }) // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. ``` renderer.js ``` document.querySelector('h1').addEventListener('click', () => { desktopManagerApi.close(); }) ``` preload.js ``` const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('desktopManagerApi', { close() { ipcRenderer.send('close') } }); ``` But, if i call `webContents.close()`, the `destroyed` event not be emitted. `webContents.isDestroyed()` is false.
https://github.com/electron/electron/issues/37419
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-27T08:07:17Z
c++
2023-03-01T10:35:06Z
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/task/single_thread_task_runner.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); } // 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()); window_->AddDraggableRegionProvider(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()); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); // 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. api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); } } 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::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->GetInspectableWebContents()->GetWebContents(); 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::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); } 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::SingleThreadTaskRunner::GetCurrentDefault()->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_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,419
[Bug]: Electron will crash when I call BrowserView.destroy().
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 21.4.2 ### Expected Behavior Electron will not exit and browserView will close. ### Actual Behavior Electron exited with code 3221225477. ### Testcase Gist URL _No response_ ### Additional Information I publish fiddle to github failed. /(ㄒoㄒ)/~~ main.js ``` // Modules to control application life and create native browser window const { app, BrowserWindow, BrowserView, ipcMain, dialog } = require('electron') const path = require('path') function createWindow() { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html') const mainView = new BrowserView({ webPreferences: { nodeIntegration: false, contextIsolation: true, } }) mainView.webContents.loadURL('https://boardmix.cn/app/') mainWindow.setBrowserView(mainView); const windowBounds = mainWindow.getContentBounds(); const viewWidth = windowBounds.width - 2; const viewHeight = windowBounds.height - 200 - 1; mainView.setBounds({ x: 1, y: 200, width: viewWidth, height: viewHeight }); ipcMain.on('close', () => { if (!mainView.webContents || mainView.webContents.isDestroyed()) { dialog.showMessageBox({message: 'webContents is destroyed'}) } else { mainView.webContents.destroy(); } }) // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. ``` renderer.js ``` document.querySelector('h1').addEventListener('click', () => { desktopManagerApi.close(); }) ``` preload.js ``` const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('desktopManagerApi', { close() { ipcRenderer.send('close') } }); ``` But, if i call `webContents.close()`, the `destroyed` event not be emitted. `webContents.isDestroyed()` is false.
https://github.com/electron/electron/issues/37419
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-27T08:07:17Z
c++
2023-03-01T10:35:06Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); // If there are observers, OnCloseContents will call Destroy() if (observers_.empty()) Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate) .Set("error", "reply was never sent") .Build(); SendReply(isolate, message); } } } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return gin::Handle<gin_helper::internal::Event>(); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,419
[Bug]: Electron will crash when I call BrowserView.destroy().
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 21.4.2 ### Expected Behavior Electron will not exit and browserView will close. ### Actual Behavior Electron exited with code 3221225477. ### Testcase Gist URL _No response_ ### Additional Information I publish fiddle to github failed. /(ㄒoㄒ)/~~ main.js ``` // Modules to control application life and create native browser window const { app, BrowserWindow, BrowserView, ipcMain, dialog } = require('electron') const path = require('path') function createWindow() { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js') } }) // and load the index.html of the app. mainWindow.loadFile('index.html') const mainView = new BrowserView({ webPreferences: { nodeIntegration: false, contextIsolation: true, } }) mainView.webContents.loadURL('https://boardmix.cn/app/') mainWindow.setBrowserView(mainView); const windowBounds = mainWindow.getContentBounds(); const viewWidth = windowBounds.width - 2; const viewHeight = windowBounds.height - 200 - 1; mainView.setBounds({ x: 1, y: 200, width: viewWidth, height: viewHeight }); ipcMain.on('close', () => { if (!mainView.webContents || mainView.webContents.isDestroyed()) { dialog.showMessageBox({message: 'webContents is destroyed'}) } else { mainView.webContents.destroy(); } }) // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. ``` renderer.js ``` document.querySelector('h1').addEventListener('click', () => { desktopManagerApi.close(); }) ``` preload.js ``` const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('desktopManagerApi', { close() { ipcRenderer.send('close') } }); ``` But, if i call `webContents.close()`, the `destroyed` event not be emitted. `webContents.isDestroyed()` is false.
https://github.com/electron/electron/issues/37419
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-27T08:07:17Z
c++
2023-03-01T10:35:06Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'path'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './lib/window-helpers'; import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; 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 = once(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view && view.webContents) { const p = once(view.webContents, 'destroyed'); view.webContents.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 typeof ElectronInternal.WebContents).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 === 'darwin' && process.arch === 'x64')('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 === 'darwin' && process.arch === 'x64')('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 correct bounds on a framed window', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); it('returns correct bounds on a frameless window', () => { 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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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.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 once(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 once(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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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 once(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 once(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')); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,378
[Bug]: No way to close a browserView
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior There should be a way to close a browserView. ### Actual Behavior Neither window.close() nor webContents.close() has any effect. You can play a video on youtube and hear the sound continue after .removeBrowserView is called. So that does not change the behavior either. Also calling window.close() in the devtools has no effect. ``` const electron = require( "electron" ) electron.app.whenReady().then(()=>{ let main = new electron.BrowserWindow({ "height" : 700, "width" : 800, show: true, }); let view = new electron.BrowserView({}); view.webContents.loadURL("https://www.youtube.com"); main.addBrowserView(view); view.setBounds({x: 0, y: 0, width: 800, height: 700}) view.webContents.openDevTools({ mode: "detach" }); setTimeout(() => { console.log("calling webContents.close()") //main.removeBrowserView(view); //view.webContents.close(); view.webContents.executeJavaScript("window.close()"); }, 5000); }) ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37378
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-22T08:43:45Z
c++
2023-03-01T10:35:06Z
shell/browser/api/electron_api_browser_view.cc
// 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/api/electron_api_browser_view.h" #include <vector> #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/render_widget_host_view.h" #include "shell/browser/api/electron_api_base_window.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/gfx_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 "ui/base/hit_test.h" #include "ui/gfx/geometry/rect.h" namespace gin { template <> struct Converter<electron::AutoResizeFlags> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::AutoResizeFlags* auto_resize_flags) { gin_helper::Dictionary params; if (!ConvertFromV8(isolate, val, &params)) { return false; } uint8_t flags = 0; bool width = false; if (params.Get("width", &width) && width) { flags |= electron::kAutoResizeWidth; } bool height = false; if (params.Get("height", &height) && height) { flags |= electron::kAutoResizeHeight; } bool horizontal = false; if (params.Get("horizontal", &horizontal) && horizontal) { flags |= electron::kAutoResizeHorizontal; } bool vertical = false; if (params.Get("vertical", &vertical) && vertical) { flags |= electron::kAutoResizeVertical; } *auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags); return true; } }; } // namespace gin namespace { int32_t GetNextId() { static int32_t next_id = 1; return next_id++; } } // namespace namespace electron::api { gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin}; BrowserView::BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options) : id_(GetNextId()) { v8::Isolate* isolate = args->isolate(); gin_helper::Dictionary web_preferences = gin::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); web_preferences.Set("type", "browserView"); v8::Local<v8::Value> value; // Copy the webContents option to webPreferences. if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } auto web_contents = WebContents::CreateFromWebPreferences(args->isolate(), web_preferences); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents.get(); api_web_contents_->AddObserver(this); Observe(web_contents->web_contents()); view_.reset( NativeBrowserView::Create(api_web_contents_->inspectable_web_contents())); } void BrowserView::SetOwnerWindow(BaseWindow* window) { // Ensure WebContents and BrowserView owner windows are in sync. if (web_contents()) web_contents()->SetOwnerWindow(window ? window->window() : nullptr); owner_window_ = window ? window->GetWeakPtr() : nullptr; } int BrowserView::NonClientHitTest(const gfx::Point& point) { gfx::Rect bounds = GetBounds(); gfx::Point local_point(point.x() - bounds.x(), point.y() - bounds.y()); SkRegion* region = api_web_contents_->draggable_region(); if (region && region->contains(local_point.x(), local_point.y())) return HTCAPTION; return HTNOWHERE; } BrowserView::~BrowserView() { if (web_contents()) { // destroy() called without closing WebContents web_contents()->RemoveObserver(this); web_contents()->Destroy(); } } void BrowserView::WebContentsDestroyed() { api_web_contents_ = nullptr; web_contents_.Reset(); Unpin(); } // static gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserView before app is ready"); return gin::Handle<BrowserView>(); } gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); auto handle = gin::CreateHandle(args->isolate(), new BrowserView(args, options)); handle->Pin(args->isolate()); return handle; } void BrowserView::SetAutoResize(AutoResizeFlags flags) { view_->SetAutoResizeFlags(flags); } void BrowserView::SetBounds(const gfx::Rect& bounds) { view_->SetBounds(bounds); } gfx::Rect BrowserView::GetBounds() { return view_->GetBounds(); } void BrowserView::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); view_->SetBackgroundColor(color); if (web_contents()) { auto* wc = web_contents()->web_contents(); wc->SetPageBaseBackgroundColor(ParseCSSColor(color_name)); auto* const rwhv = wc->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Ensure new color is stored in webPreferences, otherwise // the color will be reset on the next load via HandleNewRenderFrame. auto* web_preferences = WebContentsPreferences::From(wc); if (web_preferences) web_preferences->SetBackgroundColor(color); } } v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) { return v8::Null(isolate); } return v8::Local<v8::Value>::New(isolate, web_contents_); } // static void BrowserView::FillObjectTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::ObjectTemplateBuilder(isolate, "BrowserView", templ) .SetMethod("setAutoResize", &BrowserView::SetAutoResize) .SetMethod("setBounds", &BrowserView::SetBounds) .SetMethod("getBounds", &BrowserView::GetBounds) .SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor) .SetProperty("webContents", &BrowserView::GetWebContents) .Build(); } } // namespace electron::api namespace { using electron::api::BrowserView; 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("BrowserView", BrowserView::GetConstructor(context)); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,378
[Bug]: No way to close a browserView
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior There should be a way to close a browserView. ### Actual Behavior Neither window.close() nor webContents.close() has any effect. You can play a video on youtube and hear the sound continue after .removeBrowserView is called. So that does not change the behavior either. Also calling window.close() in the devtools has no effect. ``` const electron = require( "electron" ) electron.app.whenReady().then(()=>{ let main = new electron.BrowserWindow({ "height" : 700, "width" : 800, show: true, }); let view = new electron.BrowserView({}); view.webContents.loadURL("https://www.youtube.com"); main.addBrowserView(view); view.setBounds({x: 0, y: 0, width: 800, height: 700}) view.webContents.openDevTools({ mode: "detach" }); setTimeout(() => { console.log("calling webContents.close()") //main.removeBrowserView(view); //view.webContents.close(); view.webContents.executeJavaScript("window.close()"); }, 5000); }) ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37378
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-22T08:43:45Z
c++
2023-03-01T10:35:06Z
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/task/single_thread_task_runner.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); } // 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()); window_->AddDraggableRegionProvider(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()); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); // 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. api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); } } 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::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->GetInspectableWebContents()->GetWebContents(); 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::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); } 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::SingleThreadTaskRunner::GetCurrentDefault()->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_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,378
[Bug]: No way to close a browserView
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior There should be a way to close a browserView. ### Actual Behavior Neither window.close() nor webContents.close() has any effect. You can play a video on youtube and hear the sound continue after .removeBrowserView is called. So that does not change the behavior either. Also calling window.close() in the devtools has no effect. ``` const electron = require( "electron" ) electron.app.whenReady().then(()=>{ let main = new electron.BrowserWindow({ "height" : 700, "width" : 800, show: true, }); let view = new electron.BrowserView({}); view.webContents.loadURL("https://www.youtube.com"); main.addBrowserView(view); view.setBounds({x: 0, y: 0, width: 800, height: 700}) view.webContents.openDevTools({ mode: "detach" }); setTimeout(() => { console.log("calling webContents.close()") //main.removeBrowserView(view); //view.webContents.close(); view.webContents.executeJavaScript("window.close()"); }, 5000); }) ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37378
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-22T08:43:45Z
c++
2023-03-01T10:35:06Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); // If there are observers, OnCloseContents will call Destroy() if (observers_.empty()) Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate) .Set("error", "reply was never sent") .Build(); SendReply(isolate, message); } } } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return gin::Handle<gin_helper::internal::Event>(); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,378
[Bug]: No way to close a browserView
### 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 23.1.0 ### What operating system are you using? Windows ### Operating System Version 10.0.19042 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior There should be a way to close a browserView. ### Actual Behavior Neither window.close() nor webContents.close() has any effect. You can play a video on youtube and hear the sound continue after .removeBrowserView is called. So that does not change the behavior either. Also calling window.close() in the devtools has no effect. ``` const electron = require( "electron" ) electron.app.whenReady().then(()=>{ let main = new electron.BrowserWindow({ "height" : 700, "width" : 800, show: true, }); let view = new electron.BrowserView({}); view.webContents.loadURL("https://www.youtube.com"); main.addBrowserView(view); view.setBounds({x: 0, y: 0, width: 800, height: 700}) view.webContents.openDevTools({ mode: "detach" }); setTimeout(() => { console.log("calling webContents.close()") //main.removeBrowserView(view); //view.webContents.close(); view.webContents.executeJavaScript("window.close()"); }, 5000); }) ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37378
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-22T08:43:45Z
c++
2023-03-01T10:35:06Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'path'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './lib/window-helpers'; import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; 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 = once(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view && view.webContents) { const p = once(view.webContents, 'destroyed'); view.webContents.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 typeof ElectronInternal.WebContents).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 === 'darwin' && process.arch === 'x64')('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 === 'darwin' && process.arch === 'x64')('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 correct bounds on a framed window', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); it('returns correct bounds on a frameless window', () => { 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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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.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 once(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 once(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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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 once(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 once(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')); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,356
[Bug]: Destroyed event not emitted on close for custom BrowserView.webContents
### 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 22.3.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 22.2.1 ### Expected Behavior I've created a custom BrowserView, added it to my main BrowserWindow via `addBrowserView()`, and navigated its webContents to a file. Upon receiving a message from the renderer process, I attach a handler to the webContents' 'destroyed' event, then close the contents via `webContents.close()`. Since I'm omitting the 'waitForBeforeUnload' option in my close() call, I expect the 'destroyed' event to be emitted, and my attached handler to run. ### Actual Behavior The 'destroyed' event is not emitted, and my attached handler never run, until my main BrowserWindow is closed. ### Testcase Gist URL https://gist.github.com/mgalla10/cdff38e750ae49d01500445b019493ca ### Additional Information To repro, run the attached gist with v22.2.1 and click the "Close" button. After dismissing a message box saying "Closing page 2", that page will disappear and another "Page 2 closed" message box will appear. Run the gist again with v22.3.0 and notice that after dismissing the first message box, the page doesn't seem to disappear, and the second message box never appears.
https://github.com/electron/electron/issues/37356
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-20T21:20:50Z
c++
2023-03-01T10:35:06Z
shell/browser/api/electron_api_browser_view.cc
// 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/api/electron_api_browser_view.h" #include <vector> #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/render_widget_host_view.h" #include "shell/browser/api/electron_api_base_window.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/browser.h" #include "shell/browser/native_browser_view.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/web_contents_preferences.h" #include "shell/common/color_util.h" #include "shell/common/gin_converters/gfx_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 "ui/base/hit_test.h" #include "ui/gfx/geometry/rect.h" namespace gin { template <> struct Converter<electron::AutoResizeFlags> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::AutoResizeFlags* auto_resize_flags) { gin_helper::Dictionary params; if (!ConvertFromV8(isolate, val, &params)) { return false; } uint8_t flags = 0; bool width = false; if (params.Get("width", &width) && width) { flags |= electron::kAutoResizeWidth; } bool height = false; if (params.Get("height", &height) && height) { flags |= electron::kAutoResizeHeight; } bool horizontal = false; if (params.Get("horizontal", &horizontal) && horizontal) { flags |= electron::kAutoResizeHorizontal; } bool vertical = false; if (params.Get("vertical", &vertical) && vertical) { flags |= electron::kAutoResizeVertical; } *auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags); return true; } }; } // namespace gin namespace { int32_t GetNextId() { static int32_t next_id = 1; return next_id++; } } // namespace namespace electron::api { gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin}; BrowserView::BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options) : id_(GetNextId()) { v8::Isolate* isolate = args->isolate(); gin_helper::Dictionary web_preferences = gin::Dictionary::CreateEmpty(isolate); options.Get(options::kWebPreferences, &web_preferences); web_preferences.Set("type", "browserView"); v8::Local<v8::Value> value; // Copy the webContents option to webPreferences. if (options.Get("webContents", &value)) { web_preferences.SetHidden("webContents", value); } auto web_contents = WebContents::CreateFromWebPreferences(args->isolate(), web_preferences); web_contents_.Reset(isolate, web_contents.ToV8()); api_web_contents_ = web_contents.get(); api_web_contents_->AddObserver(this); Observe(web_contents->web_contents()); view_.reset( NativeBrowserView::Create(api_web_contents_->inspectable_web_contents())); } void BrowserView::SetOwnerWindow(BaseWindow* window) { // Ensure WebContents and BrowserView owner windows are in sync. if (web_contents()) web_contents()->SetOwnerWindow(window ? window->window() : nullptr); owner_window_ = window ? window->GetWeakPtr() : nullptr; } int BrowserView::NonClientHitTest(const gfx::Point& point) { gfx::Rect bounds = GetBounds(); gfx::Point local_point(point.x() - bounds.x(), point.y() - bounds.y()); SkRegion* region = api_web_contents_->draggable_region(); if (region && region->contains(local_point.x(), local_point.y())) return HTCAPTION; return HTNOWHERE; } BrowserView::~BrowserView() { if (web_contents()) { // destroy() called without closing WebContents web_contents()->RemoveObserver(this); web_contents()->Destroy(); } } void BrowserView::WebContentsDestroyed() { api_web_contents_ = nullptr; web_contents_.Reset(); Unpin(); } // static gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create BrowserView before app is ready"); return gin::Handle<BrowserView>(); } gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); args->GetNext(&options); auto handle = gin::CreateHandle(args->isolate(), new BrowserView(args, options)); handle->Pin(args->isolate()); return handle; } void BrowserView::SetAutoResize(AutoResizeFlags flags) { view_->SetAutoResizeFlags(flags); } void BrowserView::SetBounds(const gfx::Rect& bounds) { view_->SetBounds(bounds); } gfx::Rect BrowserView::GetBounds() { return view_->GetBounds(); } void BrowserView::SetBackgroundColor(const std::string& color_name) { SkColor color = ParseCSSColor(color_name); view_->SetBackgroundColor(color); if (web_contents()) { auto* wc = web_contents()->web_contents(); wc->SetPageBaseBackgroundColor(ParseCSSColor(color_name)); auto* const rwhv = wc->GetRenderWidgetHostView(); if (rwhv) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } // Ensure new color is stored in webPreferences, otherwise // the color will be reset on the next load via HandleNewRenderFrame. auto* web_preferences = WebContentsPreferences::From(wc); if (web_preferences) web_preferences->SetBackgroundColor(color); } } v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) { if (web_contents_.IsEmpty()) { return v8::Null(isolate); } return v8::Local<v8::Value>::New(isolate, web_contents_); } // static void BrowserView::FillObjectTemplate(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::ObjectTemplateBuilder(isolate, "BrowserView", templ) .SetMethod("setAutoResize", &BrowserView::SetAutoResize) .SetMethod("setBounds", &BrowserView::SetBounds) .SetMethod("getBounds", &BrowserView::GetBounds) .SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor) .SetProperty("webContents", &BrowserView::GetWebContents) .Build(); } } // namespace electron::api namespace { using electron::api::BrowserView; 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("BrowserView", BrowserView::GetConstructor(context)); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,356
[Bug]: Destroyed event not emitted on close for custom BrowserView.webContents
### 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 22.3.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 22.2.1 ### Expected Behavior I've created a custom BrowserView, added it to my main BrowserWindow via `addBrowserView()`, and navigated its webContents to a file. Upon receiving a message from the renderer process, I attach a handler to the webContents' 'destroyed' event, then close the contents via `webContents.close()`. Since I'm omitting the 'waitForBeforeUnload' option in my close() call, I expect the 'destroyed' event to be emitted, and my attached handler to run. ### Actual Behavior The 'destroyed' event is not emitted, and my attached handler never run, until my main BrowserWindow is closed. ### Testcase Gist URL https://gist.github.com/mgalla10/cdff38e750ae49d01500445b019493ca ### Additional Information To repro, run the attached gist with v22.2.1 and click the "Close" button. After dismissing a message box saying "Closing page 2", that page will disappear and another "Page 2 closed" message box will appear. Run the gist again with v22.3.0 and notice that after dismissing the first message box, the page doesn't seem to disappear, and the second message box never appears.
https://github.com/electron/electron/issues/37356
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-20T21:20:50Z
c++
2023-03-01T10:35:06Z
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/task/single_thread_task_runner.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); } // 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()); window_->AddDraggableRegionProvider(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()); InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. SetContentView(gin::CreateHandle<View>(isolate, web_contents_view.get())); // 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. api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); } } 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::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->GetInspectableWebContents()->GetWebContents(); 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::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); } 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::SingleThreadTaskRunner::GetCurrentDefault()->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_BINDING_CONTEXT_AWARE(electron_browser_window, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,356
[Bug]: Destroyed event not emitted on close for custom BrowserView.webContents
### 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 22.3.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 22.2.1 ### Expected Behavior I've created a custom BrowserView, added it to my main BrowserWindow via `addBrowserView()`, and navigated its webContents to a file. Upon receiving a message from the renderer process, I attach a handler to the webContents' 'destroyed' event, then close the contents via `webContents.close()`. Since I'm omitting the 'waitForBeforeUnload' option in my close() call, I expect the 'destroyed' event to be emitted, and my attached handler to run. ### Actual Behavior The 'destroyed' event is not emitted, and my attached handler never run, until my main BrowserWindow is closed. ### Testcase Gist URL https://gist.github.com/mgalla10/cdff38e750ae49d01500445b019493ca ### Additional Information To repro, run the attached gist with v22.2.1 and click the "Close" button. After dismissing a message box saying "Closing page 2", that page will disappear and another "Page 2 closed" message box will appear. Run the gist again with v22.3.0 and notice that after dismissing the first message box, the page doesn't seem to disappear, and the second message box never appears.
https://github.com/electron/electron/issues/37356
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-20T21:20:50Z
c++
2023-03-01T10:35:06Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); // If there are observers, OnCloseContents will call Destroy() if (observers_.empty()) Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate) .Set("error", "reply was never sent") .Build(); SendReply(isolate, message); } } } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return gin::Handle<gin_helper::internal::Event>(); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,356
[Bug]: Destroyed event not emitted on close for custom BrowserView.webContents
### 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 22.3.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 22.2.1 ### Expected Behavior I've created a custom BrowserView, added it to my main BrowserWindow via `addBrowserView()`, and navigated its webContents to a file. Upon receiving a message from the renderer process, I attach a handler to the webContents' 'destroyed' event, then close the contents via `webContents.close()`. Since I'm omitting the 'waitForBeforeUnload' option in my close() call, I expect the 'destroyed' event to be emitted, and my attached handler to run. ### Actual Behavior The 'destroyed' event is not emitted, and my attached handler never run, until my main BrowserWindow is closed. ### Testcase Gist URL https://gist.github.com/mgalla10/cdff38e750ae49d01500445b019493ca ### Additional Information To repro, run the attached gist with v22.2.1 and click the "Close" button. After dismissing a message box saying "Closing page 2", that page will disappear and another "Page 2 closed" message box will appear. Run the gist again with v22.3.0 and notice that after dismissing the first message box, the page doesn't seem to disappear, and the second message box never appears.
https://github.com/electron/electron/issues/37356
https://github.com/electron/electron/pull/37420
8fb0f430301578ba94b175f0b097fb2752f5ddf9
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
2023-02-20T21:20:50Z
c++
2023-03-01T10:35:06Z
spec/api-browser-view-spec.ts
import { expect } from 'chai'; import * as path from 'path'; import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main'; import { closeWindow } from './lib/window-helpers'; import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers'; import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; 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 = once(w.webContents, 'destroyed'); await closeWindow(w); w = null as any; await p; if (view && view.webContents) { const p = once(view.webContents, 'destroyed'); view.webContents.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 typeof ElectronInternal.WebContents).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 === 'darwin' && process.arch === 'x64')('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 === 'darwin' && process.arch === 'x64')('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 correct bounds on a framed window', () => { view = new BrowserView(); const bounds = { x: 10, y: 20, width: 30, height: 40 }; view.setBounds(bounds); expect(view.getBounds()).to.deep.equal(bounds); }); it('returns correct bounds on a frameless window', () => { 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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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.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 once(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 once(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.destroy()); w.addBrowserView(view1); defer(() => w.removeBrowserView(view1)); const view2 = new BrowserView(); defer(() => view2.webContents.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 once(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 once(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')); const image = await view.webContents.capturePage(); expect(image.isEmpty()).to.equal(false); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,293
[Feature Request]: Expose setDisplayMediaRequestHandler disable_local_echo flag to enable audio output during recording
### 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 want to record the electron browser window for both audio and video. - The `BrowserWindow` instance loads an external URL, which calls `window.navigator.mediaDevices.getDisplayMedia()` at some point. - We've attached a handler to `setDisplayMediaRequestHandler()` in our preload, which returns the following: `callback({ video: source, audio: mainBrowser.webContents.mainFrame });` * The video source is obtained through `desktopCapturer`, but I don't think that has anything to do with this bug. - When we assemble the stream to the `MediaRecorder` and perform recording, the browser window loses audio output when the recording starts, and resumes output when the recording stops. - The recording itself properly records video and any audio made from the window during that time. After a lot of investigation, I noticed a flag here in the PR that implements `setDisplayMediaRequestHandler()` (#30702): [shell/browser/electron_browser_context.cc](https://github.com/electron/electron/commit/221bb513265128e004a0469f3b2b1c89387ba56f#diff-fa823350727ad86e0ac08c18d6f17e24a62d653b43a08242e4608f5a8ee8e5b9R501) ``` } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) ``` And thought `disable_local_echo` might control audio loopback behavior. I compiled a custom version of electron with that flag set to `false` and repeated the above steps, which correctly allowed audio to come through the speakers while recording was happening. The recording itself retained video and audio. I am on an M2 Mac running Ventura 13.2.1. (_I have zero C++ experience and just used intuition to find this while looking at the PR for `setDisplayMediaRequestHandler` and followed the electron build guides to test my hypothesis._) ### Proposed Solution May I ask that an option be exposed for `setDisplayMediaRequestHandler` that controls the value of that particular flag? Or, have the option be part of the callback for the handler. ### Alternatives Considered Have not discovered any alternatives. Literature around `setDisplayMediaRequestHandler` is limited as it's a recently-released feature. ### Additional Information This bug ticket describes the behavior we experienced, although the context is a bit different (It references `getUserMedia` and `chrome.tabCapture`. https://bugs.chromium.org/p/chromium/issues/detail?id=1403733
https://github.com/electron/electron/issues/37293
https://github.com/electron/electron/pull/37315
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
49df19214ea3abaf0ad91adf3d374cba32abd521
2023-02-16T03:19:19Z
c++
2023-03-01T10:37:19Z
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(selectedDevice?.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. #### Event: 'serial-port-revoked' Returns: * `event` Event * `details` Object * `port` [SerialPort](structures/serial-port.md) * `frame` [WebFrameMain](web-frame-main.md) * `origin` string - The origin that the device has been revoked from. Emitted after `SerialPort.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ```js // Browser Process const { app, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.on('serial-port-revoked', (event, details) => { console.log(`Access revoked for serial device from origin ${details.origin}`) }) }) ``` ```js // Renderer Process const portConnect = async () => { // Request a port. const port = await navigator.serial.requestPort() // Wait for the serial port to open. await port.open({ baudRate: 9600 }) // ...later, revoke access to the serial port. await port.forget() } ``` #### Event: 'select-usb-device' Returns: * `event` Event * `details` Object * `deviceList` [USBDevice[]](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string (optional) Emitted when a USB device needs to be selected when a call to `navigator.usb.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.usb` 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 === 'usb') { // Add logic here to determine if permission should be given to allow USB selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions) const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.usb.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-usb-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (selectedDevice) { // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions) grantedDevices.push(selectedDevice) updateGrantedDevices(grantedDevices) } callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'usb-device-added' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a new device becomes available before the callback from `select-usb-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: 'usb-device-removed' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a device has been removed before the callback from `select-usb-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: 'usb-device-revoked' Returns: * `event` Event * `details` Object * `device` [USBDevice[]](structures/usb-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `USBDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ### 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: `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`, `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.fetch(input[, init])` * `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request) * `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional) Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Sends a request, similarly to how `fetch()` works in the renderer, using Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's HTTP stack. Example: ```js async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } ``` See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which issues requests from the [default session](#sessiondefaultsession). See the MDN documentation for [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more details. Limitations: * `net.fetch()` does not support the `data:` or `blob:` schemes. * The value of the `integrity` option is ignored. * The `.type` and `.url` values of the returned `Response` object are incorrect. #### `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. * `clipboard-sanitized-write` - Request access to write to 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. * `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API. * `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`, `serial`, or `usb`. * `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`, `serial`, or `usb`. * `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 } else if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB device 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.setBluetoothPairingHandler(handler)` _Windows_ _Linux_ * `handler` Function | null * `details` Object * `deviceId` string * `pairingKind` string - The type of pairing prompt being requested. One of the following values: * `confirm` This prompt is requesting confirmation that the Bluetooth device should be paired. * `confirmPin` This prompt is requesting confirmation that the provided PIN matches the pin displayed on the device. * `providePin` This prompt is requesting that a pin be provided for the device. * `frame` [WebFrameMain](web-frame-main.md) * `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`. * `callback` Function * `response` Object * `confirmed` boolean - `false` should be passed in if the dialog is canceled. If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate if the pairing is confirmed. If the `pairingKind` is `providePin` the value should be `true` when a value is provided. * `pin` string | null (optional) - When the `pairingKind` is `providePin` this value should be the required pin for the Bluetooth device. Sets a handler to respond to Bluetooth pairing requests. This handler allows developers to handle devices that require additional validation before pairing. When a handler is not defined, any pairing on Linux or Windows that requires additional validation will be automatically cancelled. macOS does not require a handler because macOS handles the pairing automatically. To clear the handler, call `setBluetoothPairingHandler(null)`. ```javascript const { app, BrowserWindow, ipcMain, session } = require('electron') let bluetoothPinCallback = null function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) } // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a IPC message to the renderer to prompt the user to confirm the pairing. // Note that this will require logic in the renderer to handle this message and // display a prompt to the user. mainWindow.webContents.send('bluetooth-pairing-request', details) }) app.whenReady().then(() => { createWindow() }) ``` #### `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. On macOS, this API will return whichever languages have been configured by the OS. #### `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
37,293
[Feature Request]: Expose setDisplayMediaRequestHandler disable_local_echo flag to enable audio output during recording
### 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 want to record the electron browser window for both audio and video. - The `BrowserWindow` instance loads an external URL, which calls `window.navigator.mediaDevices.getDisplayMedia()` at some point. - We've attached a handler to `setDisplayMediaRequestHandler()` in our preload, which returns the following: `callback({ video: source, audio: mainBrowser.webContents.mainFrame });` * The video source is obtained through `desktopCapturer`, but I don't think that has anything to do with this bug. - When we assemble the stream to the `MediaRecorder` and perform recording, the browser window loses audio output when the recording starts, and resumes output when the recording stops. - The recording itself properly records video and any audio made from the window during that time. After a lot of investigation, I noticed a flag here in the PR that implements `setDisplayMediaRequestHandler()` (#30702): [shell/browser/electron_browser_context.cc](https://github.com/electron/electron/commit/221bb513265128e004a0469f3b2b1c89387ba56f#diff-fa823350727ad86e0ac08c18d6f17e24a62d653b43a08242e4608f5a8ee8e5b9R501) ``` } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) ``` And thought `disable_local_echo` might control audio loopback behavior. I compiled a custom version of electron with that flag set to `false` and repeated the above steps, which correctly allowed audio to come through the speakers while recording was happening. The recording itself retained video and audio. I am on an M2 Mac running Ventura 13.2.1. (_I have zero C++ experience and just used intuition to find this while looking at the PR for `setDisplayMediaRequestHandler` and followed the electron build guides to test my hypothesis._) ### Proposed Solution May I ask that an option be exposed for `setDisplayMediaRequestHandler` that controls the value of that particular flag? Or, have the option be part of the callback for the handler. ### Alternatives Considered Have not discovered any alternatives. Literature around `setDisplayMediaRequestHandler` is limited as it's a recently-released feature. ### Additional Information This bug ticket describes the behavior we experienced, although the context is a bit different (It references `getUserMedia` and `chrome.tabCapture`. https://bugs.chromium.org/p/chromium/issues/detail?id=1403733
https://github.com/electron/electron/issues/37293
https://github.com/electron/electron/pull/37315
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
49df19214ea3abaf0ad91adf3d374cba32abd521
2023-02-16T03:19:19Z
c++
2023-03-01T10:37:19Z
shell/browser/electron_browser_context.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/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); base::PathService::Get(DIR_SESSION_DATA, &path_); if (!in_memory && !partition.empty()) path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition))); BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value::List current_dictionaries = prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).Clone(); // No configured dictionaries, the default will be en-US if (current_dictionaries.empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { devices.video_device = blink::MediaStreamDevice(request.video_type, id, name); } else if (result_dict.Get("video", &rfh)) { devices.video_device = blink::MediaStreamDevice( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8( content::WebContents::FromRenderFrameHost(rfh)->GetTitle())); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, name); } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) .ToString(), "Tab audio"); } else if (result_dict.Get("audio", &id)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, "System audio"); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(partition, in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,293
[Feature Request]: Expose setDisplayMediaRequestHandler disable_local_echo flag to enable audio output during recording
### 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 want to record the electron browser window for both audio and video. - The `BrowserWindow` instance loads an external URL, which calls `window.navigator.mediaDevices.getDisplayMedia()` at some point. - We've attached a handler to `setDisplayMediaRequestHandler()` in our preload, which returns the following: `callback({ video: source, audio: mainBrowser.webContents.mainFrame });` * The video source is obtained through `desktopCapturer`, but I don't think that has anything to do with this bug. - When we assemble the stream to the `MediaRecorder` and perform recording, the browser window loses audio output when the recording starts, and resumes output when the recording stops. - The recording itself properly records video and any audio made from the window during that time. After a lot of investigation, I noticed a flag here in the PR that implements `setDisplayMediaRequestHandler()` (#30702): [shell/browser/electron_browser_context.cc](https://github.com/electron/electron/commit/221bb513265128e004a0469f3b2b1c89387ba56f#diff-fa823350727ad86e0ac08c18d6f17e24a62d653b43a08242e4608f5a8ee8e5b9R501) ``` } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) ``` And thought `disable_local_echo` might control audio loopback behavior. I compiled a custom version of electron with that flag set to `false` and repeated the above steps, which correctly allowed audio to come through the speakers while recording was happening. The recording itself retained video and audio. I am on an M2 Mac running Ventura 13.2.1. (_I have zero C++ experience and just used intuition to find this while looking at the PR for `setDisplayMediaRequestHandler` and followed the electron build guides to test my hypothesis._) ### Proposed Solution May I ask that an option be exposed for `setDisplayMediaRequestHandler` that controls the value of that particular flag? Or, have the option be part of the callback for the handler. ### Alternatives Considered Have not discovered any alternatives. Literature around `setDisplayMediaRequestHandler` is limited as it's a recently-released feature. ### Additional Information This bug ticket describes the behavior we experienced, although the context is a bit different (It references `getUserMedia` and `chrome.tabCapture`. https://bugs.chromium.org/p/chromium/issues/detail?id=1403733
https://github.com/electron/electron/issues/37293
https://github.com/electron/electron/pull/37315
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
49df19214ea3abaf0ad91adf3d374cba32abd521
2023-02-16T03:19:19Z
c++
2023-03-01T10:37:19Z
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(selectedDevice?.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. #### Event: 'serial-port-revoked' Returns: * `event` Event * `details` Object * `port` [SerialPort](structures/serial-port.md) * `frame` [WebFrameMain](web-frame-main.md) * `origin` string - The origin that the device has been revoked from. Emitted after `SerialPort.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ```js // Browser Process const { app, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.session.on('serial-port-revoked', (event, details) => { console.log(`Access revoked for serial device from origin ${details.origin}`) }) }) ``` ```js // Renderer Process const portConnect = async () => { // Request a port. const port = await navigator.serial.requestPort() // Wait for the serial port to open. await port.open({ baudRate: 9600 }) // ...later, revoke access to the serial port. await port.forget() } ``` #### Event: 'select-usb-device' Returns: * `event` Event * `details` Object * `deviceList` [USBDevice[]](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) * `callback` Function * `deviceId` string (optional) Emitted when a USB device needs to be selected when a call to `navigator.usb.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.usb` 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 === 'usb') { // Add logic here to determine if permission should be given to allow USB selection return true } return false }) // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions) const grantedDevices = fetchGrantedDevices() win.webContents.session.setDevicePermissionHandler((details) => { if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') { if (details.device.vendorId === 123 && details.device.productId === 345) { // Always allow this type of device (this allows skipping the call to `navigator.usb.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-usb-device', (event, details, callback) => { event.preventDefault() const selectedDevice = details.deviceList.find((device) => { return device.vendorId === '9025' && device.productId === '67' }) if (selectedDevice) { // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions) grantedDevices.push(selectedDevice) updateGrantedDevices(grantedDevices) } callback(selectedDevice?.deviceId) }) }) ``` #### Event: 'usb-device-added' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a new device becomes available before the callback from `select-usb-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: 'usb-device-removed' Returns: * `event` Event * `details` Object * `device` [USBDevice](structures/usb-device.md) * `frame` [WebFrameMain](web-frame-main.md) Emitted after `navigator.usb.requestDevice` has been called and `select-usb-device` has fired if a device has been removed before the callback from `select-usb-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: 'usb-device-revoked' Returns: * `event` Event * `details` Object * `device` [USBDevice[]](structures/usb-device.md) * `origin` string (optional) - The origin that the device has been revoked from. Emitted after `USBDevice.forget()` has been called. This event can be used to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. ### 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: `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`, `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.fetch(input[, init])` * `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request) * `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional) Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Sends a request, similarly to how `fetch()` works in the renderer, using Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's HTTP stack. Example: ```js async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } ``` See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which issues requests from the [default session](#sessiondefaultsession). See the MDN documentation for [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more details. Limitations: * `net.fetch()` does not support the `data:` or `blob:` schemes. * The value of the `integrity` option is ignored. * The `.type` and `.url` values of the returned `Response` object are incorrect. #### `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. * `clipboard-sanitized-write` - Request access to write to 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. * `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API. * `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`, `serial`, or `usb`. * `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`, `serial`, or `usb`. * `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 } else if (permission === 'usb') { // Add logic here to determine if permission should be given to allow USB device 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.setBluetoothPairingHandler(handler)` _Windows_ _Linux_ * `handler` Function | null * `details` Object * `deviceId` string * `pairingKind` string - The type of pairing prompt being requested. One of the following values: * `confirm` This prompt is requesting confirmation that the Bluetooth device should be paired. * `confirmPin` This prompt is requesting confirmation that the provided PIN matches the pin displayed on the device. * `providePin` This prompt is requesting that a pin be provided for the device. * `frame` [WebFrameMain](web-frame-main.md) * `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`. * `callback` Function * `response` Object * `confirmed` boolean - `false` should be passed in if the dialog is canceled. If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate if the pairing is confirmed. If the `pairingKind` is `providePin` the value should be `true` when a value is provided. * `pin` string | null (optional) - When the `pairingKind` is `providePin` this value should be the required pin for the Bluetooth device. Sets a handler to respond to Bluetooth pairing requests. This handler allows developers to handle devices that require additional validation before pairing. When a handler is not defined, any pairing on Linux or Windows that requires additional validation will be automatically cancelled. macOS does not require a handler because macOS handles the pairing automatically. To clear the handler, call `setBluetoothPairingHandler(null)`. ```javascript const { app, BrowserWindow, ipcMain, session } = require('electron') let bluetoothPinCallback = null function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) } // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a IPC message to the renderer to prompt the user to confirm the pairing. // Note that this will require logic in the renderer to handle this message and // display a prompt to the user. mainWindow.webContents.send('bluetooth-pairing-request', details) }) app.whenReady().then(() => { createWindow() }) ``` #### `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. On macOS, this API will return whichever languages have been configured by the OS. #### `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
37,293
[Feature Request]: Expose setDisplayMediaRequestHandler disable_local_echo flag to enable audio output during recording
### 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 want to record the electron browser window for both audio and video. - The `BrowserWindow` instance loads an external URL, which calls `window.navigator.mediaDevices.getDisplayMedia()` at some point. - We've attached a handler to `setDisplayMediaRequestHandler()` in our preload, which returns the following: `callback({ video: source, audio: mainBrowser.webContents.mainFrame });` * The video source is obtained through `desktopCapturer`, but I don't think that has anything to do with this bug. - When we assemble the stream to the `MediaRecorder` and perform recording, the browser window loses audio output when the recording starts, and resumes output when the recording stops. - The recording itself properly records video and any audio made from the window during that time. After a lot of investigation, I noticed a flag here in the PR that implements `setDisplayMediaRequestHandler()` (#30702): [shell/browser/electron_browser_context.cc](https://github.com/electron/electron/commit/221bb513265128e004a0469f3b2b1c89387ba56f#diff-fa823350727ad86e0ac08c18d6f17e24a62d653b43a08242e4608f5a8ee8e5b9R501) ``` } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) ``` And thought `disable_local_echo` might control audio loopback behavior. I compiled a custom version of electron with that flag set to `false` and repeated the above steps, which correctly allowed audio to come through the speakers while recording was happening. The recording itself retained video and audio. I am on an M2 Mac running Ventura 13.2.1. (_I have zero C++ experience and just used intuition to find this while looking at the PR for `setDisplayMediaRequestHandler` and followed the electron build guides to test my hypothesis._) ### Proposed Solution May I ask that an option be exposed for `setDisplayMediaRequestHandler` that controls the value of that particular flag? Or, have the option be part of the callback for the handler. ### Alternatives Considered Have not discovered any alternatives. Literature around `setDisplayMediaRequestHandler` is limited as it's a recently-released feature. ### Additional Information This bug ticket describes the behavior we experienced, although the context is a bit different (It references `getUserMedia` and `chrome.tabCapture`. https://bugs.chromium.org/p/chromium/issues/detail?id=1403733
https://github.com/electron/electron/issues/37293
https://github.com/electron/electron/pull/37315
5e25d23794a4b3b1bda35c79fcc1b2fdd787ad69
49df19214ea3abaf0ad91adf3d374cba32abd521
2023-02-16T03:19:19Z
c++
2023-03-01T10:37:19Z
shell/browser/electron_browser_context.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/electron_browser_context.h" #include <memory> #include <utility> #include "base/barrier_closure.h" #include "base/base_paths.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/strings/escape.h" #include "base/strings/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/prefs/value_map_pref_store.h" #include "components/proxy_config/pref_proxy_config_tracker_impl.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/cors_origin_pattern_setter.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents_media_capture_id.h" #include "media/audio/audio_device_description.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_download_manager_delegate.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/special_storage_policy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/zoom_level_delegate.h" #include "shell/common/application_info.h" #include "shell/common/electron_constants.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_helper/error_thrower.h" #include "shell/common/options_switches.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/extension_pref_store.h" #include "extensions/browser/extension_pref_value_map_factory.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_system_factory.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "components/pref_registry/pref_registry_syncable.h" #include "components/user_prefs/user_prefs.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "base/i18n/rtl.h" #include "components/language/core/browser/language_prefs.h" #include "components/spellcheck/browser/pref_names.h" #include "components/spellcheck/common/spellcheck_common.h" #endif using content::BrowserThread; namespace electron { namespace { // Convert string to lower case and escape it. std::string MakePartitionName(const std::string& input) { return base::EscapePath(base::ToLowerASCII(input)); } } // namespace // static ElectronBrowserContext::BrowserContextMap& ElectronBrowserContext::browser_context_map() { static base::NoDestructor<ElectronBrowserContext::BrowserContextMap> browser_context_map; return *browser_context_map; } ElectronBrowserContext::ElectronBrowserContext(const std::string& partition, bool in_memory, base::Value::Dict options) : in_memory_pref_store_(new ValueMapPrefStore), storage_policy_(base::MakeRefCounted<SpecialStoragePolicy>()), protocol_registry_(base::WrapUnique(new ProtocolRegistry)), in_memory_(in_memory), ssl_config_(network::mojom::SSLConfig::New()) { // Read options. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache); if (auto use_cache_opt = options.FindBool("cache")) { use_cache_ = use_cache_opt.value(); } base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize), &max_cache_size_); base::PathService::Get(DIR_SESSION_DATA, &path_); if (!in_memory && !partition.empty()) path_ = path_.Append(FILE_PATH_LITERAL("Partitions")) .Append(base::FilePath::FromUTF8Unsafe( MakePartitionName(partition))); BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this); // Initialize Pref Registry. InitPrefs(); cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); extension_system_ = static_cast<extensions::ElectronExtensionSystem*>( extensions::ExtensionSystem::Get(this)); extension_system_->InitForRegularProfile(true /* extensions_enabled */); extension_system_->FinishInitialization(); } #endif } ElectronBrowserContext::~ElectronBrowserContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); NotifyWillBeDestroyed(); // Notify any keyed services of browser context destruction. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( this); ShutdownStoragePartitions(); BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, std::move(resource_context_)); } void ElectronBrowserContext::InitPrefs() { auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences")); ScopedAllowBlockingForElectron allow_blocking; PrefServiceFactory prefs_factory; scoped_refptr<JsonPrefStore> pref_store = base::MakeRefCounted<JsonPrefStore>(prefs_path); pref_store->ReadPrefs(); // Synchronous. prefs_factory.set_user_prefs(pref_store); prefs_factory.set_command_line_prefs(in_memory_pref_store()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) { auto* ext_pref_store = new ExtensionPrefStore( ExtensionPrefValueMapFactory::GetForBrowserContext(this), IsOffTheRecord()); prefs_factory.set_extension_prefs(ext_pref_store); } #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) auto registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>(); #else auto registry = base::MakeRefCounted<PrefRegistrySimple>(); #endif registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory, base::FilePath()); base::FilePath download_dir; base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir); registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory, download_dir); registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths); InspectableWebContents::RegisterPrefs(registry.get()); MediaDeviceIDSalt::RegisterPrefs(registry.get()); ZoomLevelDelegate::RegisterPrefs(registry.get()); PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!in_memory_) extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) BrowserContextDependencyManager::GetInstance() ->RegisterProfilePrefsForServices(registry.get()); language::LanguagePrefs::RegisterProfilePrefs(registry.get()); #endif prefs_ = prefs_factory.Create(registry.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) || \ BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) user_prefs::UserPrefs::Set(this, prefs_.get()); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) base::Value::List current_dictionaries = prefs()->GetList(spellcheck::prefs::kSpellCheckDictionaries).Clone(); // No configured dictionaries, the default will be en-US if (current_dictionaries.empty()) { std::string default_code = spellcheck::GetCorrespondingSpellCheckLanguage( base::i18n::GetConfiguredLocale()); if (!default_code.empty()) { base::Value::List language_codes; language_codes.Append(default_code); prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, base::Value(std::move(language_codes))); } } #endif } void ElectronBrowserContext::SetUserAgent(const std::string& user_agent) { user_agent_ = user_agent; } base::FilePath ElectronBrowserContext::GetPath() { return path_; } bool ElectronBrowserContext::IsOffTheRecord() { return in_memory_; } bool ElectronBrowserContext::CanUseHttpCache() const { return use_cache_; } int ElectronBrowserContext::GetMaxCacheSize() const { return max_cache_size_; } content::ResourceContext* ElectronBrowserContext::GetResourceContext() { if (!resource_context_) resource_context_ = std::make_unique<content::ResourceContext>(); return resource_context_.get(); } std::string ElectronBrowserContext::GetMediaDeviceIDSalt() { if (!media_device_id_salt_.get()) media_device_id_salt_ = std::make_unique<MediaDeviceIDSalt>(prefs_.get()); return media_device_id_salt_->GetSalt(); } std::unique_ptr<content::ZoomLevelDelegate> ElectronBrowserContext::CreateZoomLevelDelegate( const base::FilePath& partition_path) { if (!IsOffTheRecord()) { return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path); } return std::unique_ptr<content::ZoomLevelDelegate>(); } content::DownloadManagerDelegate* ElectronBrowserContext::GetDownloadManagerDelegate() { if (!download_manager_delegate_.get()) { auto* download_manager = this->GetDownloadManager(); download_manager_delegate_ = std::make_unique<ElectronDownloadManagerDelegate>(download_manager); } return download_manager_delegate_.get(); } content::BrowserPluginGuestManager* ElectronBrowserContext::GetGuestManager() { if (!guest_manager_) guest_manager_ = std::make_unique<WebViewManager>(); return guest_manager_.get(); } content::PlatformNotificationService* ElectronBrowserContext::GetPlatformNotificationService() { return ElectronBrowserClient::Get()->GetPlatformNotificationService(); } content::PermissionControllerDelegate* ElectronBrowserContext::GetPermissionControllerDelegate() { if (!permission_manager_.get()) permission_manager_ = std::make_unique<ElectronPermissionManager>(); return permission_manager_.get(); } storage::SpecialStoragePolicy* ElectronBrowserContext::GetSpecialStoragePolicy() { return storage_policy_.get(); } std::string ElectronBrowserContext::GetUserAgent() const { return user_agent_.value_or(ElectronBrowserClient::Get()->GetUserAgent()); } predictors::PreconnectManager* ElectronBrowserContext::GetPreconnectManager() { if (!preconnect_manager_.get()) { preconnect_manager_ = std::make_unique<predictors::PreconnectManager>(nullptr, this); } return preconnect_manager_.get(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserContext::GetURLLoaderFactory() { if (url_loader_factory_) return url_loader_factory_; mojo::PendingRemote<network::mojom::URLLoaderFactory> network_factory_remote; mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = network_factory_remote.InitWithNewPipeAndPassReceiver(); // Consult the embedder. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient> header_client; static_cast<content::ContentBrowserClient*>(ElectronBrowserClient::Get()) ->WillCreateURLLoaderFactory( this, nullptr, -1, content::ContentBrowserClient::URLLoaderFactoryType::kNavigation, url::Origin(), absl::nullopt, ukm::kInvalidSourceIdObj, &factory_receiver, &header_client, nullptr, nullptr, nullptr); network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); params->header_client = std::move(header_client); params->process_id = network::mojom::kBrowserProcessId; params->is_trusted = true; params->is_corb_enabled = false; // The tests of net module would fail if this setting is true, it seems that // the non-NetworkService implementation always has web security enabled. params->disable_web_security = false; auto* storage_partition = GetDefaultStoragePartition(); storage_partition->GetNetworkContext()->CreateURLLoaderFactory( std::move(factory_receiver), std::move(params)); url_loader_factory_ = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory_remote)); return url_loader_factory_; } content::PushMessagingService* ElectronBrowserContext::GetPushMessagingService() { return nullptr; } content::SSLHostStateDelegate* ElectronBrowserContext::GetSSLHostStateDelegate() { return nullptr; } content::BackgroundFetchDelegate* ElectronBrowserContext::GetBackgroundFetchDelegate() { return nullptr; } content::BackgroundSyncController* ElectronBrowserContext::GetBackgroundSyncController() { return nullptr; } content::BrowsingDataRemoverDelegate* ElectronBrowserContext::GetBrowsingDataRemoverDelegate() { return nullptr; } content::ClientHintsControllerDelegate* ElectronBrowserContext::GetClientHintsControllerDelegate() { return nullptr; } content::StorageNotificationService* ElectronBrowserContext::GetStorageNotificationService() { return nullptr; } content::ReduceAcceptLanguageControllerDelegate* ElectronBrowserContext::GetReduceAcceptLanguageControllerDelegate() { // Needs implementation // Refs https://chromium-review.googlesource.com/c/chromium/src/+/3687391 return nullptr; } ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } network::mojom::SSLConfigPtr ElectronBrowserContext::GetSSLConfig() { return ssl_config_.Clone(); } void ElectronBrowserContext::SetSSLConfig(network::mojom::SSLConfigPtr config) { ssl_config_ = std::move(config); if (ssl_config_client_) { ssl_config_client_->OnSSLConfigUpdated(ssl_config_.Clone()); } } void ElectronBrowserContext::SetSSLConfigClient( mojo::Remote<network::mojom::SSLConfigClient> client) { ssl_config_client_ = std::move(client); } void ElectronBrowserContext::SetDisplayMediaRequestHandler( DisplayMediaRequestHandler handler) { display_media_request_handler_ = handler; } void ElectronBrowserContext::DisplayMediaDeviceChosen( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, gin::Arguments* args) { blink::mojom::StreamDevicesSetPtr stream_devices_set = blink::mojom::StreamDevicesSet::New(); v8::Local<v8::Value> result; if (!args->GetNext(&result) || result->IsNullOrUndefined()) { std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } gin_helper::Dictionary result_dict; if (!gin::ConvertFromV8(args->isolate(), result, &result_dict)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Display Media Request streams callback must be called with null " "or a valid object"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } stream_devices_set->stream_devices.emplace_back( blink::mojom::StreamDevices::New()); blink::mojom::StreamDevices& devices = *stream_devices_set->stream_devices[0]; bool video_requested = request.video_type != blink::mojom::MediaStreamType::NO_SERVICE; bool audio_requested = request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE; bool has_video = false; if (video_requested && result_dict.Has("video")) { gin_helper::Dictionary video_dict; std::string id; std::string name; content::RenderFrameHost* rfh; if (result_dict.Get("video", &video_dict) && video_dict.Get("id", &id) && video_dict.Get("name", &name)) { devices.video_device = blink::MediaStreamDevice(request.video_type, id, name); } else if (result_dict.Get("video", &rfh)) { devices.video_device = blink::MediaStreamDevice( request.video_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID()) .ToString(), base::UTF16ToUTF8( content::WebContents::FromRenderFrameHost(rfh)->GetTitle())); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "video must be a WebFrameMain or DesktopCapturerSource"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } has_video = true; } if (audio_requested && result_dict.Has("audio")) { gin_helper::Dictionary audio_dict; std::string id; std::string name; content::RenderFrameHost* rfh; // NB. this is not permitted by the documentation, but is left here as an // "escape hatch" for providing an arbitrary name/id if needed in the // future. if (result_dict.Get("audio", &audio_dict) && audio_dict.Get("id", &id) && audio_dict.Get("name", &name)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, name); } else if (result_dict.Get("audio", &rfh)) { devices.audio_device = blink::MediaStreamDevice( request.audio_type, content::WebContentsMediaCaptureId(rfh->GetProcess()->GetID(), rfh->GetRoutingID(), /* disable_local_echo= */ true) .ToString(), "Tab audio"); } else if (result_dict.Get("audio", &id)) { devices.audio_device = blink::MediaStreamDevice(request.audio_type, id, "System audio"); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "audio must be a WebFrameMain, \"loopback\" or " "\"loopbackWithMute\""); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } } if ((video_requested && !has_video)) { gin_helper::ErrorThrower(args->isolate()) .ThrowTypeError( "Video was requested, but no video stream was provided"); std::move(callback).Run( blink::mojom::StreamDevicesSet(), blink::mojom::MediaStreamRequestResult::CAPTURE_FAILURE, nullptr); return; } std::move(callback).Run(*stream_devices_set, blink::mojom::MediaStreamRequestResult::OK, nullptr); } bool ElectronBrowserContext::ChooseDisplayMediaDevice( const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { if (!display_media_request_handler_) return false; DisplayMediaResponseCallbackJs callbackJs = base::BindOnce(&DisplayMediaDeviceChosen, request, std::move(callback)); display_media_request_handler_.Run(request, std::move(callbackJs)); return true; } void ElectronBrowserContext::GrantDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { granted_devices_[permission_type][origin].push_back( std::make_unique<base::Value>(device.Clone())); } void ElectronBrowserContext::RevokeDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return; for (auto it = origin_devices_it->second.begin(); it != origin_devices_it->second.end();) { if (DoesDeviceMatch(device, it->get(), permission_type)) { it = origin_devices_it->second.erase(it); } else { ++it; } } } bool ElectronBrowserContext::DoesDeviceMatch( const base::Value& device, const base::Value* device_to_compare, blink::PermissionType permission_type) { if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::HID) || permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::USB)) { if (device.GetDict().FindInt(kDeviceVendorIdKey) != device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) || device.GetDict().FindInt(kDeviceProductIdKey) != device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) { return false; } const auto* serial_number = device_to_compare->GetDict().FindString(kDeviceSerialNumberKey); const auto* device_serial_number = device.GetDict().FindString(kDeviceSerialNumberKey); if (serial_number && device_serial_number && *device_serial_number == *serial_number) return true; } else if (permission_type == static_cast<blink::PermissionType>( WebContentsPermissionHelper::PermissionType::SERIAL)) { #if BUILDFLAG(IS_WIN) const auto* instance_id = device.GetDict().FindString(kDeviceInstanceIdKey); const auto* port_instance_id = device_to_compare->GetDict().FindString(kDeviceInstanceIdKey); if (instance_id && port_instance_id && *instance_id == *port_instance_id) return true; #else const auto* serial_number = device.GetDict().FindString(kSerialNumberKey); const auto* port_serial_number = device_to_compare->GetDict().FindString(kSerialNumberKey); if (device.GetDict().FindInt(kVendorIdKey) != device_to_compare->GetDict().FindInt(kVendorIdKey) || device.GetDict().FindInt(kProductIdKey) != device_to_compare->GetDict().FindInt(kProductIdKey) || (serial_number && port_serial_number && *port_serial_number != *serial_number)) { return false; } #if BUILDFLAG(IS_MAC) const auto* usb_driver_key = device.GetDict().FindString(kUsbDriverKey); const auto* port_usb_driver_key = device_to_compare->GetDict().FindString(kUsbDriverKey); if (usb_driver_key && port_usb_driver_key && *usb_driver_key != *port_usb_driver_key) { return false; } #endif // BUILDFLAG(IS_MAC) return true; #endif // BUILDFLAG(IS_WIN) } return false; } bool ElectronBrowserContext::CheckDevicePermission( const url::Origin& origin, const base::Value& device, blink::PermissionType permission_type) { const auto& current_devices_it = granted_devices_.find(permission_type); if (current_devices_it == granted_devices_.end()) return false; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return false; for (const auto& device_to_compare : origin_devices_it->second) { if (DoesDeviceMatch(device, device_to_compare.get(), permission_type)) return true; } return false; } // static ElectronBrowserContext* ElectronBrowserContext::From( const std::string& partition, bool in_memory, base::Value::Dict options) { PartitionKey key(partition, in_memory); ElectronBrowserContext* browser_context = browser_context_map()[key].get(); if (browser_context) { return browser_context; } auto* new_context = new ElectronBrowserContext(partition, in_memory, std::move(options)); browser_context_map()[key] = std::unique_ptr<ElectronBrowserContext>(new_context); return new_context; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,305
[Bug]: Aspect Ratio locking and MinHeight/Width appear incompatible
### 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 22.0.0 ### What operating system are you using? macOS ### Operating System Version 13.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior IF a BW has minHeight of 300 AND an aspect ratio of X. The BW should never get smaller than 300px tall. ### Actual Behavior It's tough to describe but it appears as though minHeight is either ignored, or being scaled in some way. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37305
https://github.com/electron/electron/pull/37306
49df19214ea3abaf0ad91adf3d374cba32abd521
8f2917db0169c81d293db7e32902252612ac68f5
2023-02-16T13:45:48Z
c++
2023-03-01T15:50:14Z
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include <algorithm> #include "base/mac/mac_util.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/native_widget_mac.h" using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle; using FullScreenTransitionState = electron::NativeWindow::FullScreenTransitionState; @implementation ElectronNSWindowDelegate - (id)initWithShell:(electron::NativeWindowMac*)shell { // The views library assumes the window delegate must be an instance of // ViewsNSWindowDelegate, since we don't have a way to override the creation // of NSWindowDelegate, we have to dynamically replace the window delegate // on the fly. // TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating // window delegate. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); if ((self = [super initWithBridgedNativeWidget:bridged_view])) { shell_ = shell; is_zooming_ = false; level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level]; } return self; } #pragma mark - NSWindowDelegate - (void)windowDidChangeOcclusionState:(NSNotification*)notification { // notification.object is the window that changed its state. // It's safe to use self.window instead if you don't assign one delegate to // many windows NSWindow* window = notification.object; // check occlusion binary flag if (window.occlusionState & NSWindowOcclusionStateVisible) { // The app is visible shell_->NotifyWindowShow(); } else { // The app is not visible shell_->NotifyWindowHide(); } } // Called when the user clicks the zoom button or selects it from the Window // menu to determine the "standard size" of the window. - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)frame { if (!shell_->zoom_to_page_width()) { if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } // If the shift key is down, maximize. if ([[NSApp currentEvent] modifierFlags] & NSEventModifierFlagShift) return frame; // Get preferred width from observers. Usually the page width. int preferred_width = 0; shell_->NotifyWindowRequestPreferredWidth(&preferred_width); // Never shrink from the current size on zoom. NSRect window_frame = [window frame]; CGFloat zoomed_width = std::max(static_cast<CGFloat>(preferred_width), NSWidth(window_frame)); // |frame| determines our maximum extents. We need to set the origin of the // frame -- and only move it left if necessary. if (window_frame.origin.x + zoomed_width > NSMaxX(frame)) frame.origin.x = NSMaxX(frame) - zoomed_width; else frame.origin.x = window_frame.origin.x; // Set the width. Don't touch y or height. frame.size.width = zoomed_width; if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } - (void)windowDidBecomeMain:(NSNotification*)notification { shell_->NotifyWindowFocus(); shell_->RedrawTrafficLights(); } - (void)windowDidResignMain:(NSNotification*)notification { shell_->NotifyWindowBlur(); shell_->RedrawTrafficLights(); } - (void)windowDidBecomeKey:(NSNotification*)notification { shell_->NotifyWindowIsKeyChanged(true); shell_->RedrawTrafficLights(); } - (void)windowDidResignKey:(NSNotification*)notification { // If our app is still active and we're still the key window, ignore this // message, since it just means that a menu extra (on the "system status bar") // was activated; we'll get another |-windowDidResignKey| if we ever really // lose key window status. if ([NSApp isActive] && ([NSApp keyWindow] == [notification object])) return; shell_->NotifyWindowIsKeyChanged(false); shell_->RedrawTrafficLights(); } - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize { NSSize newSize = frameSize; double aspectRatio = shell_->GetAspectRatio(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = windowSize.height() - contentSize.height() + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); } if (!resizingHorizontally_) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); const auto widthDelta = frameSize.width - [window frame].size.width; const auto heightDelta = frameSize.height - [window frame].size.height; resizingHorizontally_ = std::abs(widthDelta) > std::abs(heightDelta); } { bool prevent_default = false; NSRect new_bounds = NSMakeRect(sender.frame.origin.x, sender.frame.origin.y, newSize.width, newSize.height); shell_->NotifyWindowWillResize(gfx::ScreenRectFromNSRect(new_bounds), *resizingHorizontally_ ? gfx::ResizeEdge::kRight : gfx::ResizeEdge::kBottom, &prevent_default); if (prevent_default) { return sender.frame.size; } } return newSize; } - (void)windowDidResize:(NSNotification*)notification { [super windowDidResize:notification]; shell_->NotifyWindowResize(); shell_->RedrawTrafficLights(); } - (void)windowWillMove:(NSNotification*)notification { NSWindow* window = [notification object]; NSSize size = [[window contentView] frame].size; NSRect new_bounds = NSMakeRect(window.frame.origin.x, window.frame.origin.y, size.width, size.height); bool prevent_default = false; // prevent_default has no effect shell_->NotifyWindowWillMove(gfx::ScreenRectFromNSRect(new_bounds), &prevent_default); } - (void)windowDidMove:(NSNotification*)notification { [super windowDidMove:notification]; // TODO(zcbenz): Remove the alias after figuring out a proper // way to dispatch move. shell_->NotifyWindowMove(); shell_->NotifyWindowMoved(); } - (void)windowWillMiniaturize:(NSNotification*)notification { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); // store the current status window level to be restored in // windowDidDeminiaturize level_ = [window level]; shell_->SetWindowLevel(NSNormalWindowLevel); shell_->UpdateWindowOriginalFrame(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->SetWindowLevel(level_); shell_->NotifyWindowRestore(); } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { is_zooming_ = true; return YES; } - (void)windowDidEndLiveResize:(NSNotification*)notification { resizingHorizontally_.reset(); shell_->NotifyWindowResized(); if (is_zooming_) { if (shell_->IsMaximized()) shell_->NotifyWindowMaximize(); else shell_->NotifyWindowUnmaximize(); is_zooming_ = false; } } - (void)windowWillEnterFullScreen:(NSNotification*)notification { // Store resizable mask so it can be restored after exiting fullscreen. is_resizable_ = shell_->HasStyleMask(NSWindowStyleMaskResizable); shell_->set_fullscreen_transition_state(FullScreenTransitionState::ENTERING); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::NONE); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::EXITING); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::NONE); shell_->SetResizable(is_resizable_); shell_->NotifyWindowLeaveFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillClose:(NSNotification*)notification { shell_->Cleanup(); shell_->NotifyWindowClosed(); // Something called -[NSWindow close] on a sheet rather than calling // -[NSWindow endSheet:] on its parent. If the modal session is not ended // then the parent will never be able to show another sheet. But calling // -endSheet: here will block the thread with an animation, so post a task. if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); NSWindow* sheetParent = [window sheetParent]; base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(base::RetainBlock(^{ [sheetParent endSheet:window]; }))); } // Clears the delegate when window is going to be closed, since EL Capitan it // is possible that the methods of delegate would get called after the window // has been closed. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell_->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); bridged_view->OnWindowWillClose(); } - (BOOL)windowShouldClose:(id)window { shell_->NotifyWindowCloseButtonClicked(); return NO; } - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { NSView* view = window.contentView; rect.origin.x = shell_->GetSheetOffsetX(); rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY(); return rect; } - (void)windowWillBeginSheet:(NSNotification*)notification { shell_->NotifyWindowSheetBegin(); } - (void)windowDidEndSheet:(NSNotification*)notification { shell_->NotifyWindowSheetEnd(); } - (IBAction)newWindowForTab:(id)sender { shell_->NotifyNewWindowForTab(); electron::Browser::Get()->NewWindowForTab(); } #pragma mark - NSTouchBarDelegate - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { if (touchBar && shell_->touch_bar()) return [shell_->touch_bar() makeItemForIdentifier:identifier]; else return nil; } #pragma mark - QLPreviewPanelDataSource - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel { return 1; } - (id<QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index { return shell_->preview_item(); } @end
closed
electron/electron
https://github.com/electron/electron
37,305
[Bug]: Aspect Ratio locking and MinHeight/Width appear incompatible
### 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 22.0.0 ### What operating system are you using? macOS ### Operating System Version 13.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior IF a BW has minHeight of 300 AND an aspect ratio of X. The BW should never get smaller than 300px tall. ### Actual Behavior It's tough to describe but it appears as though minHeight is either ignored, or being scaled in some way. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37305
https://github.com/electron/electron/pull/37306
49df19214ea3abaf0ad91adf3d374cba32abd521
8f2917db0169c81d293db7e32902252612ac68f5
2023-02-16T13:45:48Z
c++
2023-03-01T15:50:14Z
shell/browser/ui/cocoa/electron_ns_window_delegate.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include <algorithm> #include "base/mac/mac_util.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/native_widget_mac.h" using TitleBarStyle = electron::NativeWindowMac::TitleBarStyle; using FullScreenTransitionState = electron::NativeWindow::FullScreenTransitionState; @implementation ElectronNSWindowDelegate - (id)initWithShell:(electron::NativeWindowMac*)shell { // The views library assumes the window delegate must be an instance of // ViewsNSWindowDelegate, since we don't have a way to override the creation // of NSWindowDelegate, we have to dynamically replace the window delegate // on the fly. // TODO(zcbenz): Add interface in NativeWidgetMac to allow overriding creating // window delegate. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); if ((self = [super initWithBridgedNativeWidget:bridged_view])) { shell_ = shell; is_zooming_ = false; level_ = [shell_->GetNativeWindow().GetNativeNSWindow() level]; } return self; } #pragma mark - NSWindowDelegate - (void)windowDidChangeOcclusionState:(NSNotification*)notification { // notification.object is the window that changed its state. // It's safe to use self.window instead if you don't assign one delegate to // many windows NSWindow* window = notification.object; // check occlusion binary flag if (window.occlusionState & NSWindowOcclusionStateVisible) { // The app is visible shell_->NotifyWindowShow(); } else { // The app is not visible shell_->NotifyWindowHide(); } } // Called when the user clicks the zoom button or selects it from the Window // menu to determine the "standard size" of the window. - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)frame { if (!shell_->zoom_to_page_width()) { if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } // If the shift key is down, maximize. if ([[NSApp currentEvent] modifierFlags] & NSEventModifierFlagShift) return frame; // Get preferred width from observers. Usually the page width. int preferred_width = 0; shell_->NotifyWindowRequestPreferredWidth(&preferred_width); // Never shrink from the current size on zoom. NSRect window_frame = [window frame]; CGFloat zoomed_width = std::max(static_cast<CGFloat>(preferred_width), NSWidth(window_frame)); // |frame| determines our maximum extents. We need to set the origin of the // frame -- and only move it left if necessary. if (window_frame.origin.x + zoomed_width > NSMaxX(frame)) frame.origin.x = NSMaxX(frame) - zoomed_width; else frame.origin.x = window_frame.origin.x; // Set the width. Don't touch y or height. frame.size.width = zoomed_width; if (shell_->GetAspectRatio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } - (void)windowDidBecomeMain:(NSNotification*)notification { shell_->NotifyWindowFocus(); shell_->RedrawTrafficLights(); } - (void)windowDidResignMain:(NSNotification*)notification { shell_->NotifyWindowBlur(); shell_->RedrawTrafficLights(); } - (void)windowDidBecomeKey:(NSNotification*)notification { shell_->NotifyWindowIsKeyChanged(true); shell_->RedrawTrafficLights(); } - (void)windowDidResignKey:(NSNotification*)notification { // If our app is still active and we're still the key window, ignore this // message, since it just means that a menu extra (on the "system status bar") // was activated; we'll get another |-windowDidResignKey| if we ever really // lose key window status. if ([NSApp isActive] && ([NSApp keyWindow] == [notification object])) return; shell_->NotifyWindowIsKeyChanged(false); shell_->RedrawTrafficLights(); } - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize { NSSize newSize = frameSize; double aspectRatio = shell_->GetAspectRatio(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = windowSize.height() - contentSize.height() + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); } if (!resizingHorizontally_) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); const auto widthDelta = frameSize.width - [window frame].size.width; const auto heightDelta = frameSize.height - [window frame].size.height; resizingHorizontally_ = std::abs(widthDelta) > std::abs(heightDelta); } { bool prevent_default = false; NSRect new_bounds = NSMakeRect(sender.frame.origin.x, sender.frame.origin.y, newSize.width, newSize.height); shell_->NotifyWindowWillResize(gfx::ScreenRectFromNSRect(new_bounds), *resizingHorizontally_ ? gfx::ResizeEdge::kRight : gfx::ResizeEdge::kBottom, &prevent_default); if (prevent_default) { return sender.frame.size; } } return newSize; } - (void)windowDidResize:(NSNotification*)notification { [super windowDidResize:notification]; shell_->NotifyWindowResize(); shell_->RedrawTrafficLights(); } - (void)windowWillMove:(NSNotification*)notification { NSWindow* window = [notification object]; NSSize size = [[window contentView] frame].size; NSRect new_bounds = NSMakeRect(window.frame.origin.x, window.frame.origin.y, size.width, size.height); bool prevent_default = false; // prevent_default has no effect shell_->NotifyWindowWillMove(gfx::ScreenRectFromNSRect(new_bounds), &prevent_default); } - (void)windowDidMove:(NSNotification*)notification { [super windowDidMove:notification]; // TODO(zcbenz): Remove the alias after figuring out a proper // way to dispatch move. shell_->NotifyWindowMove(); shell_->NotifyWindowMoved(); } - (void)windowWillMiniaturize:(NSNotification*)notification { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); // store the current status window level to be restored in // windowDidDeminiaturize level_ = [window level]; shell_->SetWindowLevel(NSNormalWindowLevel); shell_->UpdateWindowOriginalFrame(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->SetWindowLevel(level_); shell_->NotifyWindowRestore(); } - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame { is_zooming_ = true; return YES; } - (void)windowDidEndLiveResize:(NSNotification*)notification { resizingHorizontally_.reset(); shell_->NotifyWindowResized(); if (is_zooming_) { if (shell_->IsMaximized()) shell_->NotifyWindowMaximize(); else shell_->NotifyWindowUnmaximize(); is_zooming_ = false; } } - (void)windowWillEnterFullScreen:(NSNotification*)notification { // Store resizable mask so it can be restored after exiting fullscreen. is_resizable_ = shell_->HasStyleMask(NSWindowStyleMaskResizable); shell_->set_fullscreen_transition_state(FullScreenTransitionState::ENTERING); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::NONE); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::EXITING); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::NONE); shell_->SetResizable(is_resizable_); shell_->NotifyWindowLeaveFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillClose:(NSNotification*)notification { shell_->Cleanup(); shell_->NotifyWindowClosed(); // Something called -[NSWindow close] on a sheet rather than calling // -[NSWindow endSheet:] on its parent. If the modal session is not ended // then the parent will never be able to show another sheet. But calling // -endSheet: here will block the thread with an animation, so post a task. if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); NSWindow* sheetParent = [window sheetParent]; base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(base::RetainBlock(^{ [sheetParent endSheet:window]; }))); } // Clears the delegate when window is going to be closed, since EL Capitan it // is possible that the methods of delegate would get called after the window // has been closed. auto* bridge_host = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell_->GetNativeWindow()); auto* bridged_view = bridge_host->GetInProcessNSWindowBridge(); bridged_view->OnWindowWillClose(); } - (BOOL)windowShouldClose:(id)window { shell_->NotifyWindowCloseButtonClicked(); return NO; } - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect { NSView* view = window.contentView; rect.origin.x = shell_->GetSheetOffsetX(); rect.origin.y = view.frame.size.height - shell_->GetSheetOffsetY(); return rect; } - (void)windowWillBeginSheet:(NSNotification*)notification { shell_->NotifyWindowSheetBegin(); } - (void)windowDidEndSheet:(NSNotification*)notification { shell_->NotifyWindowSheetEnd(); } - (IBAction)newWindowForTab:(id)sender { shell_->NotifyNewWindowForTab(); electron::Browser::Get()->NewWindowForTab(); } #pragma mark - NSTouchBarDelegate - (NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { if (touchBar && shell_->touch_bar()) return [shell_->touch_bar() makeItemForIdentifier:identifier]; else return nil; } #pragma mark - QLPreviewPanelDataSource - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel { return 1; } - (id<QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index { return shell_->preview_item(); } @end
closed
electron/electron
https://github.com/electron/electron
37,424
[Bug]: takeHeapSnapshot is always throwing an error
### 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 22.0.2 ### What operating system are you using? macOS ### Operating System Version macOS 12.5 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior `process.takeHeapSnapshot(path)` and `window.webContents.takeHeapSnapshot(path)` should generate a heap snapshot at the given path. ### Actual Behavior `Error: takeHeapSnapshot failed` is returned. ### Testcase Gist URL https://gist.github.com/0302cbfbd787648265b60efe85b7c3d7 ### Additional Information This provides a minimum reproducible gist, same issue as https://github.com/electron/electron/issues/28758
https://github.com/electron/electron/issues/37424
https://github.com/electron/electron/pull/37434
8f2917db0169c81d293db7e32902252612ac68f5
9b20b3a722a7b807c161813cf2b616e74aee660d
2023-02-27T14:55:15Z
c++
2023-03-01T15:50:36Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate) .Set("error", "reply was never sent") .Build(); SendReply(isolate, message); } } } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return gin::Handle<gin_helper::internal::Event>(); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,424
[Bug]: takeHeapSnapshot is always throwing an error
### 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 22.0.2 ### What operating system are you using? macOS ### Operating System Version macOS 12.5 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior `process.takeHeapSnapshot(path)` and `window.webContents.takeHeapSnapshot(path)` should generate a heap snapshot at the given path. ### Actual Behavior `Error: takeHeapSnapshot failed` is returned. ### Testcase Gist URL https://gist.github.com/0302cbfbd787648265b60efe85b7c3d7 ### Additional Information This provides a minimum reproducible gist, same issue as https://github.com/electron/electron/issues/28758
https://github.com/electron/electron/issues/37424
https://github.com/electron/electron/pull/37434
8f2917db0169c81d293db7e32902252612ac68f5
9b20b3a722a7b807c161813cf2b616e74aee660d
2023-02-27T14:55:15Z
c++
2023-03-01T15:50:36Z
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, app, BrowserView } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; 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 once(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await once(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('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); 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 = once(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 = once(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 once(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 once(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 = once(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(50).then(() => { w.webContents.send('test'); }); }); }); 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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); 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('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).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 */ }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(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 once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(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 = once(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 = once(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(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 = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(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 = once(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 = once(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 once(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 once(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 = once(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 = once(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 = once(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 = once(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 = once(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', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); 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 = once(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 = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).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 = once(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(200).then(() => { res.end(); }); }); 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 = once(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(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { 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().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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 = once(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 = once(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 = once(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 typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(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 once(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'; 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); }); }); it('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('strict-origin-when-cross-origin'); 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 = once(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 = once(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 = once(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(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); 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' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // 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('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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 () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('with custom page sizes', async () => { const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats)) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); 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); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); 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 = once(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 = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(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(async () => { 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'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { 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(); }); proxyServerPort = (await listen(proxyServer)).port; }); 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 once(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true }); const crashEvent = once(contents, 'render-process-gone'); await contents.loadURL('about:blank'); contents.forcefullyCrashRenderer(); await crashEvent; contents.destroy(); }); }); 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 = once(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('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); 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 once(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 once(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
37,424
[Bug]: takeHeapSnapshot is always throwing an error
### 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 22.0.2 ### What operating system are you using? macOS ### Operating System Version macOS 12.5 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior `process.takeHeapSnapshot(path)` and `window.webContents.takeHeapSnapshot(path)` should generate a heap snapshot at the given path. ### Actual Behavior `Error: takeHeapSnapshot failed` is returned. ### Testcase Gist URL https://gist.github.com/0302cbfbd787648265b60efe85b7c3d7 ### Additional Information This provides a minimum reproducible gist, same issue as https://github.com/electron/electron/issues/28758
https://github.com/electron/electron/issues/37424
https://github.com/electron/electron/pull/37434
8f2917db0169c81d293db7e32902252612ac68f5
9b20b3a722a7b807c161813cf2b616e74aee660d
2023-02-27T14:55:15Z
c++
2023-03-01T15:50:36Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate) .Set("error", "reply was never sent") .Build(); SendReply(isolate, message); } } } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return gin::Handle<gin_helper::internal::Event>(); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,424
[Bug]: takeHeapSnapshot is always throwing an error
### 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 22.0.2 ### What operating system are you using? macOS ### Operating System Version macOS 12.5 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior `process.takeHeapSnapshot(path)` and `window.webContents.takeHeapSnapshot(path)` should generate a heap snapshot at the given path. ### Actual Behavior `Error: takeHeapSnapshot failed` is returned. ### Testcase Gist URL https://gist.github.com/0302cbfbd787648265b60efe85b7c3d7 ### Additional Information This provides a minimum reproducible gist, same issue as https://github.com/electron/electron/issues/28758
https://github.com/electron/electron/issues/37424
https://github.com/electron/electron/pull/37434
8f2917db0169c81d293db7e32902252612ac68f5
9b20b3a722a7b807c161813cf2b616e74aee660d
2023-02-27T14:55:15Z
c++
2023-03-01T15:50:36Z
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, app, BrowserView } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; 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 once(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await once(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('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); 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 = once(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 = once(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 once(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 once(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 = once(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(50).then(() => { w.webContents.send('test'); }); }); }); 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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); 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('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).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 */ }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(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 once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(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 = once(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 = once(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(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 = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(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 = once(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 = once(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 once(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 once(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 = once(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 = once(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 = once(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 = once(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 = once(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', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); 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 = once(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 = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).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 = once(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(200).then(() => { res.end(); }); }); 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 = once(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(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { 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().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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 = once(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 = once(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 = once(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 typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(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 once(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'; 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); }); }); it('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('strict-origin-when-cross-origin'); 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 = once(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 = once(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 = once(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(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); 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' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // 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('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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 () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('with custom page sizes', async () => { const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats)) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); 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); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); 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 = once(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 = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(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(async () => { 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'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { 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(); }); proxyServerPort = (await listen(proxyServer)).port; }); 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 once(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true }); const crashEvent = once(contents, 'render-process-gone'); await contents.loadURL('about:blank'); contents.forcefullyCrashRenderer(); await crashEvent; contents.destroy(); }); }); 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 = once(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('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); 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 once(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 once(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
37,414
[Bug]: Frameless window is not draggable when running MAS build
### 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 23.1.1 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.1 ### Expected Behavior Window should be draggable. ### Actual Behavior Window is not draggable. ### Testcase Gist URL https://gist.github.com/1387d3e19cbf2717cd21bbf3befaf159 ### Additional Information To be noted, dragging works as expected on standard Electron builds but consistently fails when using Mac Apple Store builds (>= v23). @nornagon I understand you've been working on some related issues recently, please let me know if this is a known/fixed issue and I'll close this one, thanks!
https://github.com/electron/electron/issues/37414
https://github.com/electron/electron/pull/37466
692876c73740d039ac840c91c719f7e9cf3b7e76
76c825d6193e6da540b64190ff2d2298d53da5ea
2023-02-26T00:16:38Z
c++
2023-03-02T19:21:51Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; @end @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)swipeWithEvent:(NSEvent*)event { if (event.deltaY == 1.0) { shell_->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell_->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell_->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell_->NotifyWindowSwipe("left"); } } - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [[children mutableCopy] autorelease]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = [self delegate]; panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = nil; panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
37,414
[Bug]: Frameless window is not draggable when running MAS build
### 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 23.1.1 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.1 ### Expected Behavior Window should be draggable. ### Actual Behavior Window is not draggable. ### Testcase Gist URL https://gist.github.com/1387d3e19cbf2717cd21bbf3befaf159 ### Additional Information To be noted, dragging works as expected on standard Electron builds but consistently fails when using Mac Apple Store builds (>= v23). @nornagon I understand you've been working on some related issues recently, please let me know if this is a known/fixed issue and I'll close this one, thanks!
https://github.com/electron/electron/issues/37414
https://github.com/electron/electron/pull/37466
692876c73740d039ac840c91c719f7e9cf3b7e76
76c825d6193e6da540b64190ff2d2298d53da5ea
2023-02-26T00:16:38Z
c++
2023-03-02T19:21:51Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; @end @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)swipeWithEvent:(NSEvent*)event { if (event.deltaY == 1.0) { shell_->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell_->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell_->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell_->NotifyWindowSwipe("left"); } } - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [[children mutableCopy] autorelease]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = [self delegate]; panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = nil; panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
shell/browser/electron_browser_main_parts.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/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "chrome/browser/icon_manager.h" #include "chrome/browser/ui/color/chrome_color_mixers.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_child_process_host_delegate.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_utility_process.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/linux/linux_ui_getter.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "components/os_crypt/keychain_password_mac.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #include "shell/common/plugin_info.h" #endif // BUILDFLAG(ENABLE_PLUGINS) namespace electron { namespace { #if BUILDFLAG(IS_LINUX) class LinuxUiGetterImpl : public ui::LinuxUiGetter { public: LinuxUiGetterImpl() = default; ~LinuxUiGetterImpl() override = default; ui::LinuxUiTheme* GetForWindow(aura::Window* window) override { return GetForProfile(nullptr); } ui::LinuxUiTheme* GetForProfile(Profile* profile) override { return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk); } }; #endif template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(AddChromeColorMixers)); return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext()); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->isolate()->GetCurrentContext(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Create explicit microtasks runner. js_env_->CreateMicrotasksRunner(); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // Load everything. node_bindings_->LoadEnvironment(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { if (!views::LayoutProvider::Get()) { layout_provider_ = std::make_unique<views::LayoutProvider>(); } // Fetch the system locale for Electron. #if BUILDFLAG(IS_MAC) fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale()); #else fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale()); #endif auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); #if defined(USE_AURA) // NB: must be called _after_ locale resource bundle is loaded, // because ui lib makes use of it in X11 if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif // Initialize the app locale for Electron and Chromium. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); Browser::Get()->ApplyForcedRTL(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); #if BUILDFLAG(ENABLE_PLUGINS) // PluginService can only be used on the UI thread // and ContentClient::AddPlugins gets called for both browser and render // process where the latter will not have UI thread which leads to DCHECK. // Separate the WebPluginInfo registration for these processes. std::vector<content::WebPluginInfo> plugins; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->RefreshPlugins(); GetInternalPlugins(&plugins); for (const auto& plugin : plugins) plugin_service->RegisterInternalPlugin(plugin, true); #endif } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto* linux_ui = ui::GetDefaultLinuxUi(); CHECK(linux_ui); linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>(); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr); CHECK(linux_ui_theme); linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(linux_ui); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) std::string app_name = electron::Browser::Get()->GetName(); #endif #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb), content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput})); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::SingleThreadTaskRunner::GetCurrentDefault(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_MAC) KeychainPassword::GetServiceName() = app_name + " Safe Storage"; KeychainPassword::GetAccountName() = app_name; #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Shutdown utility process created with Electron API before // stopping Node.js so that exit events can be emitted. We don't let // content layer perform this action since it destroys // child process only after this step (PostMainMessageLoopRun) via // BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our // use case. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108 // // The following logic is based on // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159 // // Although content::BrowserChildProcessHostIterator is only to be called from // IO thread, it is safe to call from PostMainMessageLoopRun because thread // restrictions have been lifted. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078 for (content::BrowserChildProcessHostIterator it( content::PROCESS_TYPE_UTILITY); !it.Done(); ++it) { if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) { auto& process = it.GetData().GetProcess(); if (!process.IsValid()) continue; auto utility_process_wrapper = api::UtilityProcessWrapper::FromProcessId(process.Pid()); if (utility_process_wrapper) utility_process_wrapper->Shutdown(0 /* exit_code */); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); node::Stop(node_env_->env(), false); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
shell/renderer/electron_renderer_client.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/renderer/electron_renderer_client.h" #include <string> #include "base/command_line.h" #include "content/public/renderer/render_frame.h" #include "electron/buildflags/buildflags.h" #include "net/http/http_request_headers.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/renderer/electron_render_frame_observer.h" #include "shell/renderer/web_worker_observer.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck namespace electron { ElectronRendererClient::ElectronRendererClient() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kRenderer)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} ElectronRendererClient::~ElectronRendererClient() = default; void ElectronRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new ElectronRenderFrameObserver(render_frame, this); RendererClientBase::RenderFrameCreated(render_frame); } void ElectronRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentStart(render_frame); // Inform the document start phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-start"); } void ElectronRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentEnd(render_frame); // Inform the document end phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-end"); } void ElectronRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> renderer_context, content::RenderFrame* render_frame) { // TODO(zcbenz): Do not create Node environment if node integration is not // enabled. // Only load Node.js if we are a main frame or a devtools extension // unless Node.js support has been explicitly enabled for subframes. if (!ShouldLoadPreload(renderer_context, render_frame)) return; injected_frames_.insert(render_frame); if (!node_integration_initialized_) { node_integration_initialized_ = true; node_bindings_->Initialize(renderer_context); node_bindings_->PrepareEmbedThread(); } // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. v8::Maybe<bool> initialized = node::InitializeContext(renderer_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(renderer_context, nullptr); // If we have disabled the site instance overrides we should prevent loading // any non-context aware native module. env->options()->force_context_aware = true; // We do not want to crash the renderer process on unhandled rejections. env->options()->unhandled_rejections = "warn"; environments_.insert(env); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); gin_helper::Dictionary process_dict(env->isolate(), env->process_object()); BindProcess(env->isolate(), &process_dict, render_frame); // Load everything. node_bindings_->LoadEnvironment(env); if (node_bindings_->uv_env() == nullptr) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->StartPolling(); } } void ElectronRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; node::Environment* env = node::Environment::GetCurrent(context); if (environments_.erase(env) == 0) return; gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); // The main frame may be replaced. if (env == node_bindings_->uv_env()) node_bindings_->set_uv_env(nullptr); // Destroying the node environment will also run the uv loop, // 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. v8::MicrotaskQueue* microtask_queue = context->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); node::FreeEnvironment(env); if (node_bindings_->uv_env() == nullptr) { node::FreeIsolateData(node_bindings_->isolate_data()); node_bindings_->set_isolate_data(nullptr); } microtask_queue->set_microtasks_policy(old_policy); // ElectronBindings is tracking node environments. electron_bindings_->EnvironmentDestroyed(env); } void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread( v8::Local<v8::Context> context) { // We do not create a Node.js environment in service or shared workers // owing to an inability to customize sandbox policies in these workers // given that they're run out-of-process. auto* ec = blink::ExecutionContext::From(context); if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope()) return; // This won't be correct for in-process child windows with webPreferences // that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { // WorkerScriptReadyForEvaluationOnWorkerThread can be invoked multiple // times for the same thread, so we need to create a new observer each time // this happens. We use a ThreadLocalOwnedPointer to ensure that the old // observer for a given thread gets destructed when swapping with the new // observer in WebWorkerObserver::Create. WebWorkerObserver::Create()->WorkerScriptReadyForEvaluation(context); } } void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread( v8::Local<v8::Context> context) { auto* ec = blink::ExecutionContext::From(context); if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope()) return; // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { auto* current = WebWorkerObserver::GetCurrent(); if (current) current->ContextWillDestroy(context); } } node::Environment* ElectronRendererClient::GetEnvironment( content::RenderFrame* render_frame) const { if (injected_frames_.find(render_frame) == injected_frames_.end()) return nullptr; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); auto context = GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent()); node::Environment* env = node::Environment::GetCurrent(context); if (environments_.find(env) == environments_.end()) return nullptr; return env; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/fixtures/api/unhandled-rejection-handled.js
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/fixtures/api/unhandled-rejection.js
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/node-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as util from 'util'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import { webContents } from 'electron/main'; import { EventEmitter } from 'stream'; import { once } from 'events'; const features = process._linkedBinding('electron_common_features'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); describe('node feature', () => { const fixtures = path.join(__dirname, 'fixtures'); describe('child_process', () => { describe('child_process.fork', () => { it('Works in browser process', async () => { const child = childProcess.fork(path.join(fixtures, 'module', 'ping.js')); const message = once(child, 'message'); child.send('message'); const [msg] = await message; expect(msg).to.equal('message'); }); }); }); ifdescribe(features.isRunAsNodeEnabled())('child_process in renderer', () => { useRemoteContext(); describe('child_process.fork', () => { itremote('works in current process', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('preserves args', async (fixtures: string) => { const args = ['--expose_gc', '-test', '1']; const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process_args.js'), args); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(args).to.deep.equal(msg.slice(2)); }, [fixtures]); itremote('works in forked process', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('works in forked process when options.env is specified', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js'), [], { path: process.env.PATH }); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('has String::localeCompare working in script', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'locale-compare.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.deep.equal([0, -1, 1]); }, [fixtures]); itremote('has setImmediate working in script', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'set-immediate.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('ok'); }, [fixtures]); itremote('pipes stdio', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process-stdout.js'), { silent: true }); let data = ''; child.stdout.on('data', (chunk: any) => { data += String(chunk); }); const code = await new Promise<any>(resolve => child.once('close', resolve)); expect(code).to.equal(0); expect(data).to.equal('pipes stdio'); }, [fixtures]); itremote('works when sending a message to a process forked with the --eval argument', async () => { const source = "process.on('message', (message) => { process.send(message) })"; const forked = require('child_process').fork('--eval', [source]); const message = new Promise(resolve => forked.once('message', resolve)); forked.send('hello'); const msg = await message; expect(msg).to.equal('hello'); }); it('has the electron version in process.versions', async () => { const source = 'process.send(process.versions)'; const forked = require('child_process').fork('--eval', [source]); const [message] = await once(forked, 'message'); expect(message) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); }); describe('child_process.spawn', () => { itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => { const child = require('child_process').spawn(process.execPath, [require('path').join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: true } }); let output = ''; child.stdout.on('data', (data: any) => { output += data; }); try { await new Promise(resolve => child.stdout.once('close', resolve)); expect(JSON.parse(output)).to.deep.equal({ stdoutType: 'pipe', processType: 'undefined', window: 'undefined' }); } finally { child.kill(); } }, [fixtures]); }); describe('child_process.exec', () => { ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => { // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst). // We disable this for unsandboxed processes, which the renderer tests // are running in. If this test fails with an error like 'effective uid // is not 0', then it's likely that our patch to prevent the flag from // being set has become ineffective. const w = await getRemoteContext(); const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')'); expect(stdout).to.not.be.empty(); }); }); }); it('does not hang when using the fs module in the renderer process', async () => { const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js'); const appProcess = childProcess.spawn(process.execPath, [appPath], { cwd: path.join(mainFixturesPath, 'apps', 'libuv-hang'), stdio: 'inherit' }); const [code] = await once(appProcess, 'close'); expect(code).to.equal(0); }); describe('contexts', () => { describe('setTimeout called under Chromium event loop in browser process', () => { it('Can be scheduled in time', (done) => { setTimeout(done, 0); }); it('Can be promisified', (done) => { util.promisify(setTimeout)(0).then(done); }); }); describe('setInterval called under Chromium event loop in browser process', () => { it('can be scheduled in time', (done) => { let interval: any = null; let clearing = false; const clear = () => { if (interval === null || clearing) return; // interval might trigger while clearing (remote is slow sometimes) clearing = true; clearInterval(interval); clearing = false; interval = null; done(); }; interval = setInterval(clear, 10); }); }); const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => { const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[]; emitter.removeAllListeners(eventName); emitter.once(eventName, (...args) => { emitter.removeAllListeners(eventName); listeners.forEach((listener) => { emitter.on(eventName, listener); }); // eslint-disable-next-line standard/no-callback-literal callback(...args); }); }; describe('error thrown in main process node context', () => { it('gets emitted as a process uncaughtException event', async () => { fs.readFile(__filename, () => { throw new Error('hello'); }); const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); describe('promise rejection in main process node context', () => { it('gets emitted as a process unhandledRejection event', async () => { fs.readFile(__filename, () => { Promise.reject(new Error('hello')); }); const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); }); describe('contexts in renderer', () => { useRemoteContext(); describe('setTimeout in fs callback', () => { itremote('does not crash', async (filename: string) => { await new Promise(resolve => require('fs').readFile(filename, () => { setTimeout(resolve, 0); })); }, [__filename]); }); describe('error thrown in renderer process node context', () => { itremote('gets emitted as a process uncaughtException event', async (filename: string) => { const error = new Error('boo!'); require('fs').readFile(filename, () => { throw error; }); await new Promise<void>((resolve, reject) => { process.once('uncaughtException', (thrown) => { try { expect(thrown).to.equal(error); resolve(); } catch (e) { reject(e); } }); }); }, [__filename]); }); describe('URL handling in the renderer process', () => { itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => { const url = new URL('file://' + require('path').resolve(fixtures, 'pages', 'base-page.html')); expect(() => { require('fs').createReadStream(url); }).to.not.throw(); }, [fixtures]); }); describe('setTimeout called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); itremote('works from the timers module', async () => { await new Promise(resolve => require('timers').setTimeout(resolve, 10)); }); }); describe('setInterval called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); itremote('can be scheduled in time from timers module', async () => { const { setInterval, clearInterval } = require('timers'); await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); }); }); describe('message loop in renderer', () => { useRemoteContext(); describe('process.nextTick', () => { itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve))); itremote('works in nested calls', () => new Promise(resolve => { process.nextTick(() => { process.nextTick(() => process.nextTick(resolve)); }); })); }); describe('setImmediate', () => { itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve))); itremote('works in nested calls', () => new Promise(resolve => { setImmediate(() => { setImmediate(() => setImmediate(resolve)); }); })); }); }); ifdescribe(features.isRunAsNodeEnabled() && process.platform === 'darwin')('net.connect', () => { itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => { const socketPath = require('path').join(require('os').tmpdir(), 'electron-test.sock'); const script = require('path').join(fixtures, 'module', 'create_socket.js'); const child = require('child_process').fork(script, [socketPath]); const code = await new Promise(resolve => child.once('exit', resolve)); expect(code).to.equal(0); const client = require('net').connect(socketPath); const error = await new Promise<any>(resolve => client.once('error', resolve)); expect(error.code).to.equal('ECONNREFUSED'); }, [fixtures]); }); describe('Buffer', () => { useRemoteContext(); itremote('can be created from Blink external string', () => { const p = document.createElement('p'); p.innerText = '闲云潭影日悠悠,物换星移几度秋'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋'); expect(Buffer.byteLength(p.innerText)).to.equal(45); }); itremote('correctly parses external one-byte UTF8 string', () => { const p = document.createElement('p'); p.innerText = 'Jøhänñéß'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('Jøhänñéß'); expect(Buffer.byteLength(p.innerText)).to.equal(13); }); itremote('does not crash when creating large Buffers', () => { let buffer = Buffer.from(new Array(4096).join(' ')); expect(buffer.length).to.equal(4095); buffer = Buffer.from(new Array(4097).join(' ')); expect(buffer.length).to.equal(4096); }); itremote('does not crash for crypto operations', () => { const crypto = require('crypto'); const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ='; const key = 'q90K9yBqhWZnAMCMTOJfPQ=='; const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}'; for (let i = 0; i < 10000; ++i) { const iv = Buffer.from('0'.repeat(32), 'hex'); const input = Buffer.from(data, 'base64'); const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv); const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8'); expect(cipherText).to.equal(result); } }); itremote('does not crash when using crypto.diffieHellman() constructors', () => { const crypto = require('crypto'); crypto.createDiffieHellman('abc'); crypto.createDiffieHellman('abc', 2); // Needed to test specific DiffieHellman ctors. // eslint-disable-next-line no-octal crypto.createDiffieHellman('abc', Buffer.from([2])); // eslint-disable-next-line no-octal crypto.createDiffieHellman('abc', '123'); }); itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => { const crypto = require('crypto'); const ed448 = { crv: 'Ed448', x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA', d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n', kty: 'OKP' }; expect(() => { crypto.createPrivateKey({ key: ed448, format: 'jwk' }); }).to.throw(/Invalid JWK data/); }); }); describe('process.stdout', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdout).to.not.throw(); }); itremote('does not throw an exception when calling write()', () => { expect(() => { process.stdout.write('test'); }).to.not.throw(); }); // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win. ifdescribe(process.platform !== 'darwin')('isTTY', () => { itremote('should be undefined in the renderer process', function () { expect(process.stdout.isTTY).to.be.undefined(); }); }); }); describe('process.stdin', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdin).to.not.throw(); }); itremote('returns null when read from', () => { expect(process.stdin.read()).to.be.null(); }); }); describe('process.version', () => { itremote('should not have -pre', () => { expect(process.version.endsWith('-pre')).to.be.false(); }); }); describe('vm.runInNewContext', () => { itremote('should not crash', () => { require('vm').runInNewContext(''); }); }); describe('crypto', () => { useRemoteContext(); itremote('should list the ripemd160 hash in getHashes', () => { expect(require('crypto').getHashes()).to.include('ripemd160'); }); itremote('should be able to create a ripemd160 hash and use it', () => { const hash = require('crypto').createHash('ripemd160'); hash.update('electron-ripemd160'); expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe'); }); itremote('should list aes-{128,256}-cfb in getCiphers', () => { expect(require('crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']); }); itremote('should be able to create an aes-128-cfb cipher', () => { require('crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create an aes-256-cfb cipher', () => { require('crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => { require('crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); }); itremote('should list des-ede-cbc in getCiphers', () => { expect(require('crypto').getCiphers()).to.include('des-ede-cbc'); }); itremote('should be able to create an des-ede-cbc cipher', () => { const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex'); const iv = Buffer.from('fedcba9876543210', 'hex'); require('crypto').createCipheriv('des-ede-cbc', key, iv); }); itremote('should not crash when getting an ECDH key', () => { const ecdh = require('crypto').createECDH('prime256v1'); expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer); expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer); }); itremote('should not crash when generating DH keys or fetching DH fields', () => { const dh = require('crypto').createDiffieHellman('modp15'); expect(dh.generateKeys()).to.be.an.instanceof(Buffer); expect(dh.getPublicKey()).to.be.an.instanceof(Buffer); expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer); expect(dh.getPrime()).to.be.an.instanceof(Buffer); expect(dh.getGenerator()).to.be.an.instanceof(Buffer); }); itremote('should not crash when creating an ECDH cipher', () => { const crypto = require('crypto'); const dh = crypto.createECDH('prime256v1'); dh.generateKeys(); dh.setPrivateKey(dh.getPrivateKey()); }); }); itremote('includes the electron version in process.versions', () => { expect(process.versions) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); itremote('includes the chrome version in process.versions', () => { expect(process.versions) .to.have.own.property('chrome') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+\.\d+$/); }); describe('NODE_OPTIONS', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Fails for options disallowed by Node.js itself', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); // Exit code 9 indicates cli flag parsing failure expect(code).to.equal(9); child.kill(); }); const env = { ...process.env, NODE_OPTIONS: '--v8-options' }; child = childProcess.spawn(process.execPath, { env }); exitPromise = once(child, 'exit'); let output = ''; let success = false; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/electron: --v8-options is not allowed in NODE_OPTIONS/m.test(output)) { success = true; cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) { cleanup(); done(new Error(`Unexpected output: ${output.toString()}`)); } }); }); it('Disallows crypto-related options', (done) => { after(() => { child.kill(); }); const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' }; child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/The NODE_OPTION --use-openssl-ca is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('does allow --require in non-packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 1. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(1); }); it('does not allow --require in packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, ELECTRON_FORCE_IS_PACKAGED: 'true', NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 0. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(features.isRunAsNodeEnabled())('Node.js cli flags', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(9); child.kill(); }); child = childProcess.spawn(process.execPath, ['--force-fips'], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); }); describe('process.stdout', () => { it('is a real Node stream', () => { expect((process.stdout as any)._type).to.not.be.undefined(); }); }); describe('fs.readFile', () => { it('can accept a FileHandle as the Path argument', async () => { const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt'); const fileHandle = await fs.promises.open(filePathForHandle, 'r'); const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' }); expect(file).to.not.be.empty(); await fileHandle.close(); }); }); ifdescribe(features.isRunAsNodeEnabled())('inspector', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]> | null; afterEach(async () => { if (child && exitPromise) { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(0); } else if (child) { child.kill(); } child = null as any; exitPromise = null as any; }); it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => { child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/Debugger listening on ws:/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('Supports starting the v8 inspector with --inspect and a provided port', async () => { child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); cleanup(); if (/^Debugger listening on ws:/m.test(output)) { expect(output.trim()).to.contain(':17364', 'should be listening on port 17364'); } else { throw new Error(`Unexpected output: ${output.toString()}`); } }); it('Does not start the v8 inspector when --inspect is after a -- argument', async () => { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); if (output.trim().startsWith('Debugger listening on ws://')) { throw new Error('Inspector was started when it should not have been'); } }); // IPC Electron child process not supported on Windows. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], { stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; let output = ''; const success = false; function listener (data: Buffer) { output += data; console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim()); if (match) { cleanup(); // NOTE: temporary debug logging to try to catch flake. child.stderr.on('data', (m) => console.log(m.toString())); child.stdout.on('data', (m) => console.log(m.toString())); const w = (webContents as typeof ElectronInternal.WebContents).create(); w.loadURL('about:blank') .then(() => w.executeJavaScript(`new Promise(resolve => { const connection = new WebSocket(${JSON.stringify(match[1])}) connection.onopen = () => { connection.onclose = () => resolve() connection.close() } })`)) .then(() => { w.destroy(); child.send('plz-quit'); done(); }); } } child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) cleanup(); }); }); it('Supports js binding', async () => { child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' }, stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const [{ cmd, debuggerEnabled, success }] = await once(child, 'message'); expect(cmd).to.equal('assert'); expect(debuggerEnabled).to.be.true(); expect(success).to.be.true(); }); }); it('Can find a module using a package.json main field', () => { const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' }); expect(result.status).to.equal(0); }); ifit(features.isRunAsNodeEnabled())('handles Promise timeouts correctly', async () => { const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js'); const child = childProcess.spawn(process.execPath, [scriptPath], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); const [code, signal] = await once(child, 'exit'); expect(code).to.equal(0); expect(signal).to.equal(null); child.kill(); }); it('performs microtask checkpoint correctly', (done) => { const f3 = async () => { return new Promise((resolve, reject) => { reject(new Error('oops')); }); }; process.once('unhandledRejection', () => done('catch block is delayed to next tick')); setTimeout(() => { f3().catch(() => done()); }); }); });
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
shell/browser/electron_browser_main_parts.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/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/i18n/rtl.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "chrome/browser/icon_manager.h" #include "chrome/browser/ui/color/chrome_color_mixers.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_child_process_host_delegate.h" #include "content/public/browser/browser_child_process_host_iterator.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_utility_process.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/linux/linux_ui_getter.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "components/os_crypt/keychain_password_mac.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #include "shell/common/plugin_info.h" #endif // BUILDFLAG(ENABLE_PLUGINS) namespace electron { namespace { #if BUILDFLAG(IS_LINUX) class LinuxUiGetterImpl : public ui::LinuxUiGetter { public: LinuxUiGetterImpl() = default; ~LinuxUiGetterImpl() override = default; ui::LinuxUiTheme* GetForWindow(aura::Window* window) override { return GetForProfile(nullptr); } ui::LinuxUiTheme* GetForProfile(Profile* profile) override { return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk); } }; #endif template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) DetectOzonePlatform(); ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif ui::ColorProviderManager::Get().AppendColorProviderInitializer( base::BindRepeating(AddChromeColorMixers)); return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext()); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->isolate()->GetCurrentContext(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Create explicit microtasks runner. js_env_->CreateMicrotasksRunner(); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // Load everything. node_bindings_->LoadEnvironment(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { if (!views::LayoutProvider::Get()) { layout_provider_ = std::make_unique<views::LayoutProvider>(); } // Fetch the system locale for Electron. #if BUILDFLAG(IS_MAC) fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale()); #else fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale()); #endif auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); #if defined(USE_AURA) // NB: must be called _after_ locale resource bundle is loaded, // because ui lib makes use of it in X11 if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif // Initialize the app locale for Electron and Chromium. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); Browser::Get()->ApplyForcedRTL(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); #if BUILDFLAG(ENABLE_PLUGINS) // PluginService can only be used on the UI thread // and ContentClient::AddPlugins gets called for both browser and render // process where the latter will not have UI thread which leads to DCHECK. // Separate the WebPluginInfo registration for these processes. std::vector<content::WebPluginInfo> plugins; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->RefreshPlugins(); GetInternalPlugins(&plugins); for (const auto& plugin : plugins) plugin_service->RegisterInternalPlugin(plugin, true); #endif } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto* linux_ui = ui::GetDefaultLinuxUi(); CHECK(linux_ui); linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>(); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr); CHECK(linux_ui_theme); linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(linux_ui); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) std::string app_name = electron::Browser::Get()->GetName(); #endif #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb), content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput})); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::SingleThreadTaskRunner::GetCurrentDefault(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_MAC) KeychainPassword::GetServiceName() = app_name + " Safe Storage"; KeychainPassword::GetAccountName() = app_name; #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Shutdown utility process created with Electron API before // stopping Node.js so that exit events can be emitted. We don't let // content layer perform this action since it destroys // child process only after this step (PostMainMessageLoopRun) via // BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our // use case. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108 // // The following logic is based on // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159 // // Although content::BrowserChildProcessHostIterator is only to be called from // IO thread, it is safe to call from PostMainMessageLoopRun because thread // restrictions have been lifted. // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078 for (content::BrowserChildProcessHostIterator it( content::PROCESS_TYPE_UTILITY); !it.Done(); ++it) { if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) { auto& process = it.GetData().GetProcess(); if (!process.IsValid()) continue; auto utility_process_wrapper = api::UtilityProcessWrapper::FromProcessId(process.Pid()); if (utility_process_wrapper) utility_process_wrapper->Shutdown(0 /* exit_code */); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); node::Stop(node_env_->env(), false); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
shell/renderer/electron_renderer_client.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/renderer/electron_renderer_client.h" #include <string> #include "base/command_line.h" #include "content/public/renderer/render_frame.h" #include "electron/buildflags/buildflags.h" #include "net/http/http_request_headers.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/renderer/electron_render_frame_observer.h" #include "shell/renderer/web_worker_observer.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck namespace electron { ElectronRendererClient::ElectronRendererClient() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kRenderer)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} ElectronRendererClient::~ElectronRendererClient() = default; void ElectronRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new ElectronRenderFrameObserver(render_frame, this); RendererClientBase::RenderFrameCreated(render_frame); } void ElectronRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentStart(render_frame); // Inform the document start phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-start"); } void ElectronRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentEnd(render_frame); // Inform the document end phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-end"); } void ElectronRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> renderer_context, content::RenderFrame* render_frame) { // TODO(zcbenz): Do not create Node environment if node integration is not // enabled. // Only load Node.js if we are a main frame or a devtools extension // unless Node.js support has been explicitly enabled for subframes. if (!ShouldLoadPreload(renderer_context, render_frame)) return; injected_frames_.insert(render_frame); if (!node_integration_initialized_) { node_integration_initialized_ = true; node_bindings_->Initialize(renderer_context); node_bindings_->PrepareEmbedThread(); } // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. v8::Maybe<bool> initialized = node::InitializeContext(renderer_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(renderer_context, nullptr); // If we have disabled the site instance overrides we should prevent loading // any non-context aware native module. env->options()->force_context_aware = true; // We do not want to crash the renderer process on unhandled rejections. env->options()->unhandled_rejections = "warn"; environments_.insert(env); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); gin_helper::Dictionary process_dict(env->isolate(), env->process_object()); BindProcess(env->isolate(), &process_dict, render_frame); // Load everything. node_bindings_->LoadEnvironment(env); if (node_bindings_->uv_env() == nullptr) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->StartPolling(); } } void ElectronRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; node::Environment* env = node::Environment::GetCurrent(context); if (environments_.erase(env) == 0) return; gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); // The main frame may be replaced. if (env == node_bindings_->uv_env()) node_bindings_->set_uv_env(nullptr); // Destroying the node environment will also run the uv loop, // 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. v8::MicrotaskQueue* microtask_queue = context->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); node::FreeEnvironment(env); if (node_bindings_->uv_env() == nullptr) { node::FreeIsolateData(node_bindings_->isolate_data()); node_bindings_->set_isolate_data(nullptr); } microtask_queue->set_microtasks_policy(old_policy); // ElectronBindings is tracking node environments. electron_bindings_->EnvironmentDestroyed(env); } void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread( v8::Local<v8::Context> context) { // We do not create a Node.js environment in service or shared workers // owing to an inability to customize sandbox policies in these workers // given that they're run out-of-process. auto* ec = blink::ExecutionContext::From(context); if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope()) return; // This won't be correct for in-process child windows with webPreferences // that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { // WorkerScriptReadyForEvaluationOnWorkerThread can be invoked multiple // times for the same thread, so we need to create a new observer each time // this happens. We use a ThreadLocalOwnedPointer to ensure that the old // observer for a given thread gets destructed when swapping with the new // observer in WebWorkerObserver::Create. WebWorkerObserver::Create()->WorkerScriptReadyForEvaluation(context); } } void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread( v8::Local<v8::Context> context) { auto* ec = blink::ExecutionContext::From(context); if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope()) return; // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { auto* current = WebWorkerObserver::GetCurrent(); if (current) current->ContextWillDestroy(context); } } node::Environment* ElectronRendererClient::GetEnvironment( content::RenderFrame* render_frame) const { if (injected_frames_.find(render_frame) == injected_frames_.end()) return nullptr; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); auto context = GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent()); node::Environment* env = node::Environment::GetCurrent(context); if (environments_.find(env) == environments_.end()) return nullptr; return env; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/fixtures/api/unhandled-rejection-handled.js
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/fixtures/api/unhandled-rejection.js
closed
electron/electron
https://github.com/electron/electron
36,829
[Bug]: When logging unhandled rejection stack, stack is logged twice
### 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 22.0.0 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 22.10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When adding an unhandledrejection listener that prints error.stack, the error stack should only be printed once. ```js const handleUnhandledRejection = (reason) => { console.error(`Unhandled Rejection: ${reason.stack}`); }; const main = async () => { process.on("unhandledRejection", handleUnhandledRejection); throw new Error("oops"); }; main(); ``` This is the output in NodeJS: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 ``` ### Actual Behavior In Electron, the unhandled rejection stack is printed twice: ``` Unhandled Rejection: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (node:14838) UnhandledPromiseRejectionWarning: Error: oops at main (/tmp/electron-unhandled-rejection-bug/index.js:7:9) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/index.js:10:1) at Module._compile (node:internal/modules/cjs/loader:1141:14) at Module._extensions..js (node:internal/modules/cjs/loader:1196:10) at Module.load (node:internal/modules/cjs/loader:1011:32) at Module._load (node:internal/modules/cjs/loader:846:12) at f._load (node:electron/js2c/asar_bundle:2:13328) at loadApplicationPackage (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:121:16) at Object.<anonymous> (/tmp/electron-unhandled-rejection-bug/node_modules/electron/dist/resources/default_app.asar/main.js:233:9) at Module._compile (node:internal/modules/cjs/loader:1141:14) (Use `electron --trace-warnings ...` to show where the warning was created) (node:14838) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) ``` Overall, the NodeJS output is cleaner / easier to understand. ### Testcase Gist URL https://github.com/SimonSiefke/electron-unhandled-rejection-bug ### Additional Information ## Possible solution Replacing https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/shell/browser/electron_browser_main_parts.cc#L281-L282 with an unhandled rejection handler next to this function https://github.com/electron/electron/blob/90af7d7fe2fc70984404474feec4ac2c827794fe/lib/browser/init.ts#L22 ```js process.on('unhandledRejection', function (error) { // Do nothing if the user has a custom unhandled rejection handler. if (process.listenerCount('unhandledRejection') > 1) { return; } import('electron') .then(({ dialog }) => { const stack = error.stack ? error.stack : `${error.name}: ${error.message}`; const message = 'Unhandled Rejection\n' + stack; dialog.showErrorBox('A JavaScript error occurred in the main process', message); }); }); ``` would keep the current behaviour of not crashing the main process on unhandled rejections ## Related issues - https://github.com/electron/electron/issues/36528
https://github.com/electron/electron/issues/36829
https://github.com/electron/electron/pull/37464
17ccb3c6ecca1b16fb3e10504ffe0135b4e1794c
829fb4f586ee4f0c5b6bbbc6ae9c9853a710eba6
2023-01-08T18:29:36Z
c++
2023-03-06T10:04:43Z
spec/node-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as util from 'util'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import { webContents } from 'electron/main'; import { EventEmitter } from 'stream'; import { once } from 'events'; const features = process._linkedBinding('electron_common_features'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); describe('node feature', () => { const fixtures = path.join(__dirname, 'fixtures'); describe('child_process', () => { describe('child_process.fork', () => { it('Works in browser process', async () => { const child = childProcess.fork(path.join(fixtures, 'module', 'ping.js')); const message = once(child, 'message'); child.send('message'); const [msg] = await message; expect(msg).to.equal('message'); }); }); }); ifdescribe(features.isRunAsNodeEnabled())('child_process in renderer', () => { useRemoteContext(); describe('child_process.fork', () => { itremote('works in current process', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('preserves args', async (fixtures: string) => { const args = ['--expose_gc', '-test', '1']; const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process_args.js'), args); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(args).to.deep.equal(msg.slice(2)); }, [fixtures]); itremote('works in forked process', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('works in forked process when options.env is specified', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'fork_ping.js'), [], { path: process.env.PATH }); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('message'); }, [fixtures]); itremote('has String::localeCompare working in script', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'locale-compare.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.deep.equal([0, -1, 1]); }, [fixtures]); itremote('has setImmediate working in script', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'set-immediate.js')); const message = new Promise<any>(resolve => child.once('message', resolve)); child.send('message'); const msg = await message; expect(msg).to.equal('ok'); }, [fixtures]); itremote('pipes stdio', async (fixtures: string) => { const child = require('child_process').fork(require('path').join(fixtures, 'module', 'process-stdout.js'), { silent: true }); let data = ''; child.stdout.on('data', (chunk: any) => { data += String(chunk); }); const code = await new Promise<any>(resolve => child.once('close', resolve)); expect(code).to.equal(0); expect(data).to.equal('pipes stdio'); }, [fixtures]); itremote('works when sending a message to a process forked with the --eval argument', async () => { const source = "process.on('message', (message) => { process.send(message) })"; const forked = require('child_process').fork('--eval', [source]); const message = new Promise(resolve => forked.once('message', resolve)); forked.send('hello'); const msg = await message; expect(msg).to.equal('hello'); }); it('has the electron version in process.versions', async () => { const source = 'process.send(process.versions)'; const forked = require('child_process').fork('--eval', [source]); const [message] = await once(forked, 'message'); expect(message) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); }); describe('child_process.spawn', () => { itremote('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async (fixtures: string) => { const child = require('child_process').spawn(process.execPath, [require('path').join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: true } }); let output = ''; child.stdout.on('data', (data: any) => { output += data; }); try { await new Promise(resolve => child.stdout.once('close', resolve)); expect(JSON.parse(output)).to.deep.equal({ stdoutType: 'pipe', processType: 'undefined', window: 'undefined' }); } finally { child.kill(); } }, [fixtures]); }); describe('child_process.exec', () => { ifit(process.platform === 'linux')('allows executing a setuid binary from non-sandboxed renderer', async () => { // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst). // We disable this for unsandboxed processes, which the renderer tests // are running in. If this test fails with an error like 'effective uid // is not 0', then it's likely that our patch to prevent the flag from // being set has become ineffective. const w = await getRemoteContext(); const stdout = await w.webContents.executeJavaScript('require(\'child_process\').execSync(\'sudo --help\')'); expect(stdout).to.not.be.empty(); }); }); }); it('does not hang when using the fs module in the renderer process', async () => { const appPath = path.join(mainFixturesPath, 'apps', 'libuv-hang', 'main.js'); const appProcess = childProcess.spawn(process.execPath, [appPath], { cwd: path.join(mainFixturesPath, 'apps', 'libuv-hang'), stdio: 'inherit' }); const [code] = await once(appProcess, 'close'); expect(code).to.equal(0); }); describe('contexts', () => { describe('setTimeout called under Chromium event loop in browser process', () => { it('Can be scheduled in time', (done) => { setTimeout(done, 0); }); it('Can be promisified', (done) => { util.promisify(setTimeout)(0).then(done); }); }); describe('setInterval called under Chromium event loop in browser process', () => { it('can be scheduled in time', (done) => { let interval: any = null; let clearing = false; const clear = () => { if (interval === null || clearing) return; // interval might trigger while clearing (remote is slow sometimes) clearing = true; clearInterval(interval); clearing = false; interval = null; done(); }; interval = setInterval(clear, 10); }); }); const suspendListeners = (emitter: EventEmitter, eventName: string, callback: (...args: any[]) => void) => { const listeners = emitter.listeners(eventName) as ((...args: any[]) => void)[]; emitter.removeAllListeners(eventName); emitter.once(eventName, (...args) => { emitter.removeAllListeners(eventName); listeners.forEach((listener) => { emitter.on(eventName, listener); }); // eslint-disable-next-line standard/no-callback-literal callback(...args); }); }; describe('error thrown in main process node context', () => { it('gets emitted as a process uncaughtException event', async () => { fs.readFile(__filename, () => { throw new Error('hello'); }); const result = await new Promise(resolve => suspendListeners(process, 'uncaughtException', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); describe('promise rejection in main process node context', () => { it('gets emitted as a process unhandledRejection event', async () => { fs.readFile(__filename, () => { Promise.reject(new Error('hello')); }); const result = await new Promise(resolve => suspendListeners(process, 'unhandledRejection', (error) => { resolve(error.message); })); expect(result).to.equal('hello'); }); }); }); describe('contexts in renderer', () => { useRemoteContext(); describe('setTimeout in fs callback', () => { itremote('does not crash', async (filename: string) => { await new Promise(resolve => require('fs').readFile(filename, () => { setTimeout(resolve, 0); })); }, [__filename]); }); describe('error thrown in renderer process node context', () => { itremote('gets emitted as a process uncaughtException event', async (filename: string) => { const error = new Error('boo!'); require('fs').readFile(filename, () => { throw error; }); await new Promise<void>((resolve, reject) => { process.once('uncaughtException', (thrown) => { try { expect(thrown).to.equal(error); resolve(); } catch (e) { reject(e); } }); }); }, [__filename]); }); describe('URL handling in the renderer process', () => { itremote('can successfully handle WHATWG URLs constructed by Blink', (fixtures: string) => { const url = new URL('file://' + require('path').resolve(fixtures, 'pages', 'base-page.html')); expect(() => { require('fs').createReadStream(url); }).to.not.throw(); }, [fixtures]); }); describe('setTimeout called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); itremote('works from the timers module', async () => { await new Promise(resolve => require('timers').setTimeout(resolve, 10)); }); }); describe('setInterval called under blink env in renderer process', () => { itremote('can be scheduled in time', async () => { await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); itremote('can be scheduled in time from timers module', async () => { const { setInterval, clearInterval } = require('timers'); await new Promise<void>(resolve => { const id = setInterval(() => { clearInterval(id); resolve(); }, 10); }); }); }); }); describe('message loop in renderer', () => { useRemoteContext(); describe('process.nextTick', () => { itremote('emits the callback', () => new Promise(resolve => process.nextTick(resolve))); itremote('works in nested calls', () => new Promise(resolve => { process.nextTick(() => { process.nextTick(() => process.nextTick(resolve)); }); })); }); describe('setImmediate', () => { itremote('emits the callback', () => new Promise(resolve => setImmediate(resolve))); itremote('works in nested calls', () => new Promise(resolve => { setImmediate(() => { setImmediate(() => setImmediate(resolve)); }); })); }); }); ifdescribe(features.isRunAsNodeEnabled() && process.platform === 'darwin')('net.connect', () => { itremote('emit error when connect to a socket path without listeners', async (fixtures: string) => { const socketPath = require('path').join(require('os').tmpdir(), 'electron-test.sock'); const script = require('path').join(fixtures, 'module', 'create_socket.js'); const child = require('child_process').fork(script, [socketPath]); const code = await new Promise(resolve => child.once('exit', resolve)); expect(code).to.equal(0); const client = require('net').connect(socketPath); const error = await new Promise<any>(resolve => client.once('error', resolve)); expect(error.code).to.equal('ECONNREFUSED'); }, [fixtures]); }); describe('Buffer', () => { useRemoteContext(); itremote('can be created from Blink external string', () => { const p = document.createElement('p'); p.innerText = '闲云潭影日悠悠,物换星移几度秋'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋'); expect(Buffer.byteLength(p.innerText)).to.equal(45); }); itremote('correctly parses external one-byte UTF8 string', () => { const p = document.createElement('p'); p.innerText = 'Jøhänñéß'; const b = Buffer.from(p.innerText); expect(b.toString()).to.equal('Jøhänñéß'); expect(Buffer.byteLength(p.innerText)).to.equal(13); }); itremote('does not crash when creating large Buffers', () => { let buffer = Buffer.from(new Array(4096).join(' ')); expect(buffer.length).to.equal(4095); buffer = Buffer.from(new Array(4097).join(' ')); expect(buffer.length).to.equal(4096); }); itremote('does not crash for crypto operations', () => { const crypto = require('crypto'); const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ='; const key = 'q90K9yBqhWZnAMCMTOJfPQ=='; const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}'; for (let i = 0; i < 10000; ++i) { const iv = Buffer.from('0'.repeat(32), 'hex'); const input = Buffer.from(data, 'base64'); const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv); const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8'); expect(cipherText).to.equal(result); } }); itremote('does not crash when using crypto.diffieHellman() constructors', () => { const crypto = require('crypto'); crypto.createDiffieHellman('abc'); crypto.createDiffieHellman('abc', 2); // Needed to test specific DiffieHellman ctors. // eslint-disable-next-line no-octal crypto.createDiffieHellman('abc', Buffer.from([2])); // eslint-disable-next-line no-octal crypto.createDiffieHellman('abc', '123'); }); itremote('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => { const crypto = require('crypto'); const ed448 = { crv: 'Ed448', x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA', d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n', kty: 'OKP' }; expect(() => { crypto.createPrivateKey({ key: ed448, format: 'jwk' }); }).to.throw(/Invalid JWK data/); }); }); describe('process.stdout', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdout).to.not.throw(); }); itremote('does not throw an exception when calling write()', () => { expect(() => { process.stdout.write('test'); }).to.not.throw(); }); // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win. ifdescribe(process.platform !== 'darwin')('isTTY', () => { itremote('should be undefined in the renderer process', function () { expect(process.stdout.isTTY).to.be.undefined(); }); }); }); describe('process.stdin', () => { useRemoteContext(); itremote('does not throw an exception when accessed', () => { expect(() => process.stdin).to.not.throw(); }); itremote('returns null when read from', () => { expect(process.stdin.read()).to.be.null(); }); }); describe('process.version', () => { itremote('should not have -pre', () => { expect(process.version.endsWith('-pre')).to.be.false(); }); }); describe('vm.runInNewContext', () => { itremote('should not crash', () => { require('vm').runInNewContext(''); }); }); describe('crypto', () => { useRemoteContext(); itremote('should list the ripemd160 hash in getHashes', () => { expect(require('crypto').getHashes()).to.include('ripemd160'); }); itremote('should be able to create a ripemd160 hash and use it', () => { const hash = require('crypto').createHash('ripemd160'); hash.update('electron-ripemd160'); expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe'); }); itremote('should list aes-{128,256}-cfb in getCiphers', () => { expect(require('crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']); }); itremote('should be able to create an aes-128-cfb cipher', () => { require('crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create an aes-256-cfb cipher', () => { require('crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef'); }); itremote('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => { require('crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); require('crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567')); }); itremote('should list des-ede-cbc in getCiphers', () => { expect(require('crypto').getCiphers()).to.include('des-ede-cbc'); }); itremote('should be able to create an des-ede-cbc cipher', () => { const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex'); const iv = Buffer.from('fedcba9876543210', 'hex'); require('crypto').createCipheriv('des-ede-cbc', key, iv); }); itremote('should not crash when getting an ECDH key', () => { const ecdh = require('crypto').createECDH('prime256v1'); expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer); expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer); }); itremote('should not crash when generating DH keys or fetching DH fields', () => { const dh = require('crypto').createDiffieHellman('modp15'); expect(dh.generateKeys()).to.be.an.instanceof(Buffer); expect(dh.getPublicKey()).to.be.an.instanceof(Buffer); expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer); expect(dh.getPrime()).to.be.an.instanceof(Buffer); expect(dh.getGenerator()).to.be.an.instanceof(Buffer); }); itremote('should not crash when creating an ECDH cipher', () => { const crypto = require('crypto'); const dh = crypto.createECDH('prime256v1'); dh.generateKeys(); dh.setPrivateKey(dh.getPrivateKey()); }); }); itremote('includes the electron version in process.versions', () => { expect(process.versions) .to.have.own.property('electron') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+(\S*)?$/); }); itremote('includes the chrome version in process.versions', () => { expect(process.versions) .to.have.own.property('chrome') .that.is.a('string') .and.matches(/^\d+\.\d+\.\d+\.\d+$/); }); describe('NODE_OPTIONS', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Fails for options disallowed by Node.js itself', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); // Exit code 9 indicates cli flag parsing failure expect(code).to.equal(9); child.kill(); }); const env = { ...process.env, NODE_OPTIONS: '--v8-options' }; child = childProcess.spawn(process.execPath, { env }); exitPromise = once(child, 'exit'); let output = ''; let success = false; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/electron: --v8-options is not allowed in NODE_OPTIONS/m.test(output)) { success = true; cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) { cleanup(); done(new Error(`Unexpected output: ${output.toString()}`)); } }); }); it('Disallows crypto-related options', (done) => { after(() => { child.kill(); }); const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: '--use-openssl-ca' }; child = childProcess.spawn(process.execPath, ['--enable-logging', appPath], { env }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/The NODE_OPTION --use-openssl-ca is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('does allow --require in non-packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 1. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(1); }); it('does not allow --require in packaged apps', async () => { const appPath = path.join(fixtures, 'module', 'noop.js'); const env = { ...process.env, ELECTRON_FORCE_IS_PACKAGED: 'true', NODE_OPTIONS: `--require=${path.join(fixtures, 'module', 'fail.js')}` }; // App should exit with code 0. const child = childProcess.spawn(process.execPath, [appPath], { env }); const [code] = await once(child, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(features.isRunAsNodeEnabled())('Node.js cli flags', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]>; it('Prohibits crypto-related flags in ELECTRON_RUN_AS_NODE mode', (done) => { after(async () => { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(9); child.kill(); }); child = childProcess.spawn(process.execPath, ['--force-fips'], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/.*The Node.js cli flag --force-fips is not supported in Electron/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); }); describe('process.stdout', () => { it('is a real Node stream', () => { expect((process.stdout as any)._type).to.not.be.undefined(); }); }); describe('fs.readFile', () => { it('can accept a FileHandle as the Path argument', async () => { const filePathForHandle = path.resolve(mainFixturesPath, 'dogs-running.txt'); const fileHandle = await fs.promises.open(filePathForHandle, 'r'); const file = await fs.promises.readFile(fileHandle, { encoding: 'utf8' }); expect(file).to.not.be.empty(); await fileHandle.close(); }); }); ifdescribe(features.isRunAsNodeEnabled())('inspector', () => { let child: childProcess.ChildProcessWithoutNullStreams; let exitPromise: Promise<any[]> | null; afterEach(async () => { if (child && exitPromise) { const [code, signal] = await exitPromise; expect(signal).to.equal(null); expect(code).to.equal(0); } else if (child) { child.kill(); } child = null as any; exitPromise = null as any; }); it('Supports starting the v8 inspector with --inspect/--inspect-brk', (done) => { child = childProcess.spawn(process.execPath, ['--inspect-brk', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); let output = ''; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; const listener = (data: Buffer) => { output += data; if (/Debugger listening on ws:/m.test(output)) { cleanup(); done(); } }; child.stderr.on('data', listener); child.stdout.on('data', listener); }); it('Supports starting the v8 inspector with --inspect and a provided port', async () => { child = childProcess.spawn(process.execPath, ['--inspect=17364', path.join(fixtures, 'module', 'run-as-node.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); cleanup(); if (/^Debugger listening on ws:/m.test(output)) { expect(output.trim()).to.contain(':17364', 'should be listening on port 17364'); } else { throw new Error(`Unexpected output: ${output.toString()}`); } }); it('Does not start the v8 inspector when --inspect is after a -- argument', async () => { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'noop.js'), '--', '--inspect']); exitPromise = once(child, 'exit'); let output = ''; const listener = (data: Buffer) => { output += data; }; child.stderr.on('data', listener); child.stdout.on('data', listener); await once(child, 'exit'); if (output.trim().startsWith('Debugger listening on ws://')) { throw new Error('Inspector was started when it should not have been'); } }); // IPC Electron child process not supported on Windows. ifit(process.platform !== 'win32')('does not crash when quitting with the inspector connected', function (done) { child = childProcess.spawn(process.execPath, [path.join(fixtures, 'module', 'delay-exit'), '--inspect=0'], { stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const cleanup = () => { child.stderr.removeListener('data', listener); child.stdout.removeListener('data', listener); }; let output = ''; const success = false; function listener (data: Buffer) { output += data; console.log(data.toString()); // NOTE: temporary debug logging to try to catch flake. const match = /^Debugger listening on (ws:\/\/.+:\d+\/.+)\n/m.exec(output.trim()); if (match) { cleanup(); // NOTE: temporary debug logging to try to catch flake. child.stderr.on('data', (m) => console.log(m.toString())); child.stdout.on('data', (m) => console.log(m.toString())); const w = (webContents as typeof ElectronInternal.WebContents).create(); w.loadURL('about:blank') .then(() => w.executeJavaScript(`new Promise(resolve => { const connection = new WebSocket(${JSON.stringify(match[1])}) connection.onopen = () => { connection.onclose = () => resolve() connection.close() } })`)) .then(() => { w.destroy(); child.send('plz-quit'); done(); }); } } child.stderr.on('data', listener); child.stdout.on('data', listener); child.on('exit', () => { if (!success) cleanup(); }); }); it('Supports js binding', async () => { child = childProcess.spawn(process.execPath, ['--inspect', path.join(fixtures, 'module', 'inspector-binding.js')], { env: { ELECTRON_RUN_AS_NODE: 'true' }, stdio: ['ipc'] }) as childProcess.ChildProcessWithoutNullStreams; exitPromise = once(child, 'exit'); const [{ cmd, debuggerEnabled, success }] = await once(child, 'message'); expect(cmd).to.equal('assert'); expect(debuggerEnabled).to.be.true(); expect(success).to.be.true(); }); }); it('Can find a module using a package.json main field', () => { const result = childProcess.spawnSync(process.execPath, [path.resolve(fixtures, 'api', 'electron-main-module', 'app.asar')], { stdio: 'inherit' }); expect(result.status).to.equal(0); }); ifit(features.isRunAsNodeEnabled())('handles Promise timeouts correctly', async () => { const scriptPath = path.join(fixtures, 'module', 'node-promise-timer.js'); const child = childProcess.spawn(process.execPath, [scriptPath], { env: { ELECTRON_RUN_AS_NODE: 'true' } }); const [code, signal] = await once(child, 'exit'); expect(code).to.equal(0); expect(signal).to.equal(null); child.kill(); }); it('performs microtask checkpoint correctly', (done) => { const f3 = async () => { return new Promise((resolve, reject) => { reject(new Error('oops')); }); }; process.once('unhandledRejection', () => done('catch block is delayed to next tick')); setTimeout(() => { f3().catch(() => done()); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00:24Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00:24Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } void SendError(const std::string& msg) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build(); SendReply(isolate, message); } } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) SendError("reply was never sent"); } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) { if (callback) { // We must always invoke the callback if present. ReplyChannel::Create(isolate, std::move(callback)) ->SendError("WebContents was destroyed"); } return gin::Handle<gin_helper::internal::Event>(); } gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); if (!file.IsValid()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid file path " + #if BUILDFLAG(IS_WIN) base::WideToUTF8(file_path.value())); #else file_path.value()); #endif return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid webContents main frame"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with nonexistent render frame"); 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("Failed to take heap snapshot"); } }, 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00: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, app, BrowserView } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; 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 once(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await once(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('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); 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 = once(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 = once(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 once(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 once(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 = once(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(50).then(() => { w.webContents.send('test'); }); }); }); 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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); 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('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).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 */ }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(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 once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(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 = once(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 = once(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(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 = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(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 = once(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 = once(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 once(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 once(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 = once(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 = once(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 = once(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 = once(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 = once(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', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); 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 = once(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 = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).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 = once(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(200).then(() => { res.end(); }); }); 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 = once(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(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { 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().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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 = once(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 = once(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 = once(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 typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(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 once(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'; 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); }); }); it('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('strict-origin-when-cross-origin'); 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 = once(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 = once(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 = once(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 badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); 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(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); 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' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // 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('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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 () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('with custom page sizes', async () => { const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats)) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); 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); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); 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 = once(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 = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(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(async () => { 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'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { 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(); }); proxyServerPort = (await listen(proxyServer)).port; }); 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 once(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true }); const crashEvent = once(contents, 'render-process-gone'); await contents.loadURL('about:blank'); contents.forcefullyCrashRenderer(); await crashEvent; contents.destroy(); }); }); 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 = once(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('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); 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 once(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 once(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
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00:24Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00:24Z
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/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/optional_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/thread_restrictions.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_result.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 #if !IS_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; } void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, base::ScopedClosureRunner capture_handle, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); capture_handle.RunAndReset(); } 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. ScopedAllowBlockingForElectron allow_blocking; #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::Dict& file_system_paths = pref_service->GetDict(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; for (auto it : file_system_paths) { 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::kExtensionSidePanel: 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); // Nothing to do with ZoomController, but this function gets called in all // init cases! content::RenderViewHost* host = web_contents->GetRenderViewHost(); if (host) host->GetWidget()->AddInputEventObserver(this); } 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 (web_contents()) { content::RenderViewHost* host = web_contents()->GetRenderViewHost(); if (host) host->GetWidget()->RemoveInputEventObserver(this); } 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())); } } void WebContents::Close(absl::optional<gin_helper::Dictionary> options) { bool dispatch_beforeunload = false; if (options) options->Get("waitForBeforeUnload", &dispatch_beforeunload); if (dispatch_beforeunload && web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) { NotifyUserActivation(); web_contents()->DispatchBeforeUnload(false /* auto_cancel */); } else { web_contents()->Close(); } } 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(); Destroy(); } 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) { // For backwards compatibility, pretend that `kRawKeyDown` events are // actually `kKeyDown`. content::NativeWebKeyboardEvent tweaked_event(event); if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); bool prevent_default = Emit("before-input-event", tweaked_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 { if (!owner_window()) return false; return owner_window()->IsFullscreen() || is_html_fullscreen(); } 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) { auto maybe_color = web_preferences->GetBackgroundColor(); bool guest = IsGuest() || type_ == Type::kBrowserView; // If webPreferences has no color stored we need to explicitly set guest // webContents background color to transparent. auto bg_color = maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE); web_contents()->SetPageBaseBackgroundColor(bg_color); SetBackgroundColor(rwhv, bg_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) { if (new_host->IsInPrimaryMainFrame()) { if (old_host) old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this); if (new_host) new_host->GetRenderWidgetHost()->AddInputEventObserver(this); } // 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::FromRenderFrameHost(new_host); 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_name, 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(); content::RenderFrameHost* initiator_frame_host = navigation_handle->GetInitiatorFrameToken().has_value() ? content::RenderFrameHost::FromFrameToken( navigation_handle->GetInitiatorProcessID(), navigation_handle->GetInitiatorFrameToken().value()) : nullptr; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); gin_helper::Dictionary dict(isolate, event_object); dict.Set("url", url); dict.Set("isSameDocument", is_same_document); dict.Set("isMainFrame", is_main_frame); dict.Set("frame", frame_host); dict.SetGetter("initiator", initiator_frame_host); EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); return event->GetDefaultPrevented(); } 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"); } } // This object wraps the InvokeCallback so that if it gets GC'd by V8, we can // still call the callback and send an error. Not doing so causes a Mojo DCHECK, // since Mojo requires callbacks to be called before they are destroyed. class ReplyChannel : public gin::Wrappable<ReplyChannel> { public: using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback; static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate, InvokeCallback callback) { return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback))); } // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override { return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate) .SetMethod("sendReply", &ReplyChannel::SendReply); } const char* GetTypeName() override { return "ReplyChannel"; } void SendError(const std::string& msg) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); // If there's no current context, it means we're shutting down, so we // don't need to send an event. if (!isolate->GetCurrentContext().IsEmpty()) { v8::HandleScope scope(isolate); auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build(); SendReply(isolate, message); } } private: explicit ReplyChannel(InvokeCallback callback) : callback_(std::move(callback)) {} ~ReplyChannel() override { if (callback_) SendError("reply was never sent"); } bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) { if (!callback_) return false; blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, arg, &message)) { return false; } std::move(callback_).Run(std::move(message)); return true; } InvokeCallback callback_; }; gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin}; gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender( v8::Isolate* isolate, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback) { v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) { if (callback) { // We must always invoke the callback if present. ReplyChannel::Create(isolate, std::move(callback)) ->SendError("WebContents was destroyed"); } return gin::Handle<gin_helper::internal::Event>(); } gin::Handle<gin_helper::internal::Event> event = gin_helper::internal::Event::New(isolate); gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>()); if (callback) dict.Set("_replyChannel", ReplyChannel::Create(isolate, std::move(callback))); if (frame) { dict.Set("frameId", frame->GetRoutingID()); dict.Set("processId", frame->GetProcess()->GetID()); } return event; } 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) { draggable_region_ = DraggableRegionsToSkRegion(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. #if !IS_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"; } #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 bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } 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().FindDouble("paperWidth"); auto paper_height = settings.GetDict().FindDouble("paperHeight"); auto margin_top = settings.GetDict().FindDouble("marginTop"); auto margin_bottom = settings.GetDict().FindDouble("marginBottom"); auto margin_left = settings.GetDict().FindDouble("marginLeft"); auto margin_right = settings.GetDict().FindDouble("marginRight"); 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, print_to_pdf::PdfPrintResult print_result, scoped_refptr<base::RefCountedMemory> data) { if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) { promise.RejectWithErrorMessage( "Failed to generate PDF: " + print_to_pdf::PdfPrintResultToString(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)) { // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); 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::ScopedAllowApplicationTasksInNativeNestedLoop 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) { gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); gfx::Rect rect; args->GetNext(&rect); bool stay_hidden = false; bool stay_awake = false; if (args && args->Length() == 2) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("stayHidden", &stay_hidden); options.Get("stayAwake", &stay_awake); } } 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) auto capture_handle = web_contents()->IncrementCapturerCount( rect.size(), stay_hidden, stay_awake); // 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), std::move(capture_handle))); return handle; } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const ui::Cursor& 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(); } content::RenderFrameHost* WebContents::Opener() { return web_contents()->GetOpener(); } 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(); } void WebContents::OnInputEvent(const blink::WebInputEvent& event) { Emit("input-event", event); } 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(); ScopedAllowBlockingForElectron allow_blocking; uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; // The snapshot file is passed to an untrusted process. flags = base::File::AddFlagsForPassingToUntrustedProcess(flags); base::File file(file_path, flags); if (!file.IsValid()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid file path " + #if BUILDFLAG(IS_WIN) base::WideToUTF8(file_path.value())); #else file_path.value()); #endif return handle; } auto* frame_host = web_contents()->GetPrimaryMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with invalid webContents main frame"); return handle; } if (!frame_host->IsRenderFrameLive()) { promise.RejectWithErrorMessage( "Failed to take heap snapshot with nonexistent render frame"); 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("Failed to take heap snapshot"); } }, 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 is_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 is_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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Set(path.AsUTF8Unsafe(), 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()); ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update->Remove(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->GetList()) { 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::DevToolsOpenInNewTab(const std::string& url) { Emit("devtools-open-url", url); } 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 void 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. gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("close", &WebContents::Close) .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("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) .SetProperty("opener", &WebContents::Opener) .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; using electron::api::WebFrameMain; 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> WebContentsFromFrame(v8::Isolate* isolate, WebFrameMain* web_frame) { content::RenderFrameHost* rfh = web_frame->render_frame_host(); content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh); WebContents* contents = WebContents::From(source); 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("fromFrame", &WebContentsFromFrame); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,352
[Feature Request]: Add event to WebContents to react to changes of `isCurrentlyAudible`
### 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 Chromium only shows the button to mute/unmute a tab when it actually has media playing. Once the media has paused, the button will eventually fade away. Electron does not offer a way to react to this change. ### Proposed Solution Either a single change event like `audible-change` or two symmetrical events along the lines of `did-become-audible` and `stopped-being-audible`. ### Alternatives Considered Poll `isCurrentlyAudible` ### Additional Information _No response_
https://github.com/electron/electron/issues/37352
https://github.com/electron/electron/pull/37366
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
512e56baf75bce86aef11184af881cff67d8e6a2
2023-02-20T12:29:43Z
c++
2023-03-06T16:00: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, app, BrowserView } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, defer, waitUntil, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; 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 once(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await once(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('fromFrame()', () => { it('returns WebContents for mainFrame', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); }); it('throws when passing invalid argument', async () => { let errored = false; try { webContents.fromFrame({} as any); } catch { errored = true; } expect(errored).to.be.true(); }); }); 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 = once(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 = once(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 once(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 once(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 = once(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(50).then(() => { w.webContents.send('test'); }); }); }); 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; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); 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('resolves when navigating within the page', async () => { await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await setTimeout(); await expect(w.loadURL(w.getURL() + '#foo')).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 */ }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 }); const { port } = await listen(s); 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 = once(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = once(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 once(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await setTimeout(); const devToolsClosed = once(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 = once(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 = once(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = once(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 = once(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = once(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ once(w.webContents, 'devtools-opened'), once(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 = once(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 = once(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 once(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 once(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 = once(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 = once(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 = once(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 = once(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 = once(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', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const event = once(w.webContents, 'devtools-opened'); w.webContents.inspectElement(10, 10); await event; }); }); 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 = once(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 = once(w.webContents, 'focus'); w.webContents.focus(); await expect(focusPromise).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 = once(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(200).then(() => { res.end(); }); }); 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 = once(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(async () => { server = http.createServer((req, res) => { setTimeout().then(() => res.end('hey')); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener when using "noopener"', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); it('can get opener with a[target=_blank][rel=opener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'opener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame); }); it('has no opener with a[target=_blank][rel=noopener]', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const childPromise = once(w.webContents, 'did-create-window'); w.webContents.executeJavaScript(`(function() { const a = document.createElement('a'); a.target = '_blank'; a.rel = 'noopener'; a.href = 'about:blank'; a.click(); }())`, true); const [childWindow] = await childPromise; expect(childWindow.webContents.opener).to.be.null(); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before(async () => { 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().then(respond); }); serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); 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 = once(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 = once(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 = once(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 = once(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 = once(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 typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); const destroyed = once(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 once(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'; 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); }); }); it('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('strict-origin-when-cross-origin'); 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 = once(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 = once(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 = once(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 badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path'); const promise = w.webContents.takeHeapSnapshot(badPath); return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`); }); it('fails with invalid render process', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); w.webContents.destroy(); const promise = w.webContents.takeHeapSnapshot(filePath); return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame'); }); }); 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(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); 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' }; await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); // 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('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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 () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); 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(); } }); it('can print a PDF with default settings', async () => { await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('with custom page sizes', async () => { const paperFormats: Record<string, ElectronInternal.PageSize> = { letter: { width: 8.5, height: 11 }, legal: { width: 8.5, height: 14 }, tabloid: { width: 11, height: 17 }, ledger: { width: 17, height: 11 }, a0: { width: 33.1, height: 46.8 }, a1: { width: 23.4, height: 33.1 }, a2: { width: 16.54, height: 23.4 }, a3: { width: 11.7, height: 16.54 }, a4: { width: 8.27, height: 11.7 }, a5: { width: 5.83, height: 8.27 }, a6: { width: 4.13, height: 5.83 } }; await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); for (const format of Object.keys(paperFormats)) { const data = await w.webContents.printToPDF({ pageSize: format }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2] / 72; const height = page.view[3] / 72; const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon; expect(approxEq(width, paperFormats[format].width)).to.be.true(); expect(approxEq(height, paperFormats[format].height)).to.be.true(); } }); it('with custom header and footer', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ displayHeaderFooter: true, headerTemplate: '<div>I\'m a PDF header</div>', footerTemplate: '<div>I\'m a PDF footer</div>' }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); const { items } = await page.getTextContent(); // Check that generated PDF contains a header. const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text)); expect(containsText(/I'm a PDF header/)).to.be.true(); expect(containsText(/I'm a PDF footer/)).to.be.true(); }); it('in landscape mode', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html')); const data = await w.webContents.printToPDF({ landscape: true }); const doc = await pdfjs.getDocument(data).promise; const page = await doc.getPage(1); // page.view is [top, left, width, height]. const width = page.view[2]; const height = page.view[3]; expect(width).to.be.greaterThan(height); }); it('with custom page ranges', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html')); 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); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ webPreferences: { sandbox: true } }); // TODO(codebytere): figure out why this workaround is needed and remove. // It is not germane to the actual test. await w.loadFile(path.join(fixturesPath, 'blank.html')); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true); 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 = once(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 = once(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = once(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = once(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(async () => { 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'); }); ({ port: serverPort, url: serverUrl } = await listen(server)); }); before(async () => { 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(); }); proxyServerPort = (await listen(proxyServer)).port; }); 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 once(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await once(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', async () => { const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true }); const crashEvent = once(contents, 'render-process-gone'); await contents.loadURL('about:blank'); contents.forcefullyCrashRenderer(); await crashEvent; contents.destroy(); }); }); 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 = once(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('close() method', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('closes when close() is called after loading a page', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('can be GCed before loading a page', async () => { const v8Util = process._linkedBinding('electron_common_v8_util'); let registry: FinalizationRegistry<unknown> | null = null; const cleanedUp = new Promise<number>(resolve => { registry = new FinalizationRegistry(resolve as any); }); (() => { const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); defer(() => clearInterval(i)); expect(await cleanedUp).to.equal(42); }); it('causes its parent browserwindow to be closed', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const closed = once(w, 'closed'); w.webContents.close(); await closed; expect(w.isDestroyed()).to.be.true(); }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); const destroyed = once(w, 'destroyed'); w.close(); await destroyed; expect(w.isDestroyed()).to.be.true(); }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = once(w, 'will-prevent-unload'); w.close({ waitForBeforeUnload: true }); await willPreventUnload; expect(w.isDestroyed()).to.be.false(); }); it('overriding beforeunload prevention results in webcontents close', async () => { const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); const destroyed = once(w, 'destroyed'); w.close({ waitForBeforeUnload: true }); await destroyed; expect(w.isDestroyed()).to.be.true(); }); }); 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 once(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 once(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
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
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 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 upload_list_add_loadsync_method.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 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 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 fix_crash_loading_non-standard_schemes_in_iframes.patch fix_return_v8_value_from_localframe_requestexecutescript.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch fix_tray_icon_gone_on_lock_screen.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch fix_x11_window_restore_minimized_maximized_window.patch
closed
electron/electron
https://github.com/electron/electron
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
patches/chromium/chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
closed
electron/electron
https://github.com/electron/electron
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
shell/browser/feature_list.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 "electron/shell/browser/feature_list.h" #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "components/spellcheck/common/spellcheck_features.h" #include "content/public/common/content_features.h" #include "electron/buildflags/buildflags.h" #include "media/base/media_switches.h" #include "net/base/features.h" #include "services/network/public/cpp/features.h" #if BUILDFLAG(IS_MAC) #include "device/base/features.h" // nogncheck #endif namespace electron { void InitializeFeatureList() { auto* cmd_line = base::CommandLine::ForCurrentProcess(); auto enable_features = cmd_line->GetSwitchValueASCII(::switches::kEnableFeatures); auto disable_features = cmd_line->GetSwitchValueASCII(::switches::kDisableFeatures); // Disable creation of spare renderer process with site-per-process mode, // it interferes with our process preference tracking for non sandboxed mode. // Can be reenabled when our site instance policy is aligned with chromium // when node integration is enabled. disable_features += std::string(",") + features::kSpareRendererForSitePerProcess.name; #if BUILDFLAG(IS_MAC) // Needed for WebUSB implementation enable_features += std::string(",") + device::kNewUsbBackend.name; #endif #if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) disable_features += std::string(",") + media::kPictureInPicture.name; #endif #if BUILDFLAG(IS_WIN) // Disable async spellchecker suggestions for Windows, which causes // an empty suggestions list to be returned disable_features += std::string(",") + spellcheck::kWinRetrieveSuggestionsOnlyOnDemand.name; #endif base::FeatureList::InitializeInstance(enable_features, disable_features); } void InitializeFieldTrials() { auto* cmd_line = base::CommandLine::ForCurrentProcess(); auto force_fieldtrials = cmd_line->GetSwitchValueASCII(::switches::kForceFieldTrials); base::FieldTrialList::CreateTrialsFromString(force_fieldtrials); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
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 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 upload_list_add_loadsync_method.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 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 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 fix_crash_loading_non-standard_schemes_in_iframes.patch fix_return_v8_value_from_localframe_requestexecutescript.patch create_browser_v8_snapshot_file_name_fuse.patch feat_configure_launch_options_for_service_process.patch feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch preconnect_manager.patch fix_remove_caption-removing_style_call.patch build_allow_electron_to_use_exec_script.patch build_only_use_the_mas_build_config_in_the_required_components.patch fix_tray_icon_gone_on_lock_screen.patch chore_introduce_blocking_api_for_electron.patch chore_patch_out_partition_attribute_dcheck_for_webviews.patch expose_v8initializer_codegenerationcheckcallbackinmainthread.patch chore_patch_out_profile_methods_in_profile_selections_cc.patch fix_x11_window_restore_minimized_maximized_window.patch
closed
electron/electron
https://github.com/electron/electron
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
patches/chromium/chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
closed
electron/electron
https://github.com/electron/electron
36,615
[Bug]: WebUSB API device list is always empty (attached devices are ignored).
### 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 23.0.0-alpha.1 ### What operating system are you using? macOS ### Operating System Version Ventura 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Electron should detect my Novation Launchpad X (a class-compliant, USB MIDI device). ### Actual Behavior The device shows up in `chrome://usb-internals` (in stock Chrome), but when I call `navigator.usb.getDevices` in Electron, the device does not appear in the device list. The device list is always empty. ### Testcase Gist URL _No response_ ### Additional Information Codewise, I basically have this in my `index.js` file: ``` js const { app, BrowserWindow } = require("electron"); app.whenReady().then(function() { const selectDevice = function(event, details, callback) { console.log("device list:", details.deviceList); // this array is always empty event.preventDefault(); }; const renderer = new BrowserWindow(options); // note: `options` is defined IRL renderer.webContents.session.setPermissionCheckHandler(() => true); renderer.webContents.session.on("select-usb-device", selectDevice); }); ``` In the renderer process, I just have a call to `navigator.usb.requestDevice` (inside a `keydown` event listener that only exists to ensure that the call is in response to a user gesture). Note: The filters I'm passing to the WebUSB API are empty (though I tried Novation's ID (`0x1235`) too).
https://github.com/electron/electron/issues/36615
https://github.com/electron/electron/pull/37441
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
efde7a140bc48e0e3e08404f41f6179c26858ce4
2022-12-08T19:23:44Z
c++
2023-03-07T17:40:40Z
shell/browser/feature_list.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 "electron/shell/browser/feature_list.h" #include <string> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "components/spellcheck/common/spellcheck_features.h" #include "content/public/common/content_features.h" #include "electron/buildflags/buildflags.h" #include "media/base/media_switches.h" #include "net/base/features.h" #include "services/network/public/cpp/features.h" #if BUILDFLAG(IS_MAC) #include "device/base/features.h" // nogncheck #endif namespace electron { void InitializeFeatureList() { auto* cmd_line = base::CommandLine::ForCurrentProcess(); auto enable_features = cmd_line->GetSwitchValueASCII(::switches::kEnableFeatures); auto disable_features = cmd_line->GetSwitchValueASCII(::switches::kDisableFeatures); // Disable creation of spare renderer process with site-per-process mode, // it interferes with our process preference tracking for non sandboxed mode. // Can be reenabled when our site instance policy is aligned with chromium // when node integration is enabled. disable_features += std::string(",") + features::kSpareRendererForSitePerProcess.name; #if BUILDFLAG(IS_MAC) // Needed for WebUSB implementation enable_features += std::string(",") + device::kNewUsbBackend.name; #endif #if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) disable_features += std::string(",") + media::kPictureInPicture.name; #endif #if BUILDFLAG(IS_WIN) // Disable async spellchecker suggestions for Windows, which causes // an empty suggestions list to be returned disable_features += std::string(",") + spellcheck::kWinRetrieveSuggestionsOnlyOnDemand.name; #endif base::FeatureList::InitializeInstance(enable_features, disable_features); } void InitializeFieldTrials() { auto* cmd_line = base::CommandLine::ForCurrentProcess(); auto force_fieldtrials = cmd_line->GetSwitchValueASCII(::switches::kForceFieldTrials); base::FieldTrialList::CreateTrialsFromString(force_fieldtrials); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
docs/api/native-image.md
# nativeImage > Create tray, dock, and application icons using PNG or JPG files. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) In Electron, for the APIs that take images, you can pass either file paths or `NativeImage` instances. An empty image will be used when `null` is passed. For example, when creating a tray or setting a window's icon, you can pass an image file path as a `string`: ```javascript const { BrowserWindow, Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }) console.log(appIcon, win) ``` Or read the image from the clipboard, which returns a `NativeImage`: ```javascript const { clipboard, Tray } = require('electron') const image = clipboard.readImage() const appIcon = new Tray(image) console.log(appIcon) ``` ## Supported Formats Currently `PNG` and `JPEG` image formats are supported. `PNG` is recommended because of its support for transparency and lossless compression. On Windows, you can also load `ICO` icons from file paths. For best visual quality, it is recommended to include at least the following sizes in the: * Small icon * 16x16 (100% DPI scale) * 20x20 (125% DPI scale) * 24x24 (150% DPI scale) * 32x32 (200% DPI scale) * Large icon * 32x32 (100% DPI scale) * 40x40 (125% DPI scale) * 48x48 (150% DPI scale) * 64x64 (200% DPI scale) * 256x256 Check the *Size requirements* section in [this article][icons]. [icons]:https://msdn.microsoft.com/en-us/library/windows/desktop/dn742485(v=vs.85).aspx ## High Resolution Image On platforms that have high-DPI support such as Apple Retina displays, you can append `@2x` after image's base filename to mark it as a high resolution image. For example, if `icon.png` is a normal image that has standard resolution, then `[email protected]` will be treated as a high resolution image that has double DPI density. If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes. For example: ```plaintext images/ ├── icon.png ├── [email protected] └── [email protected] ``` ```javascript const { Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') console.log(appIcon) ``` The following suffixes for DPI are also supported: * `@1x` * `@1.25x` * `@1.33x` * `@1.4x` * `@1.5x` * `@1.8x` * `@2x` * `@2.5x` * `@3x` * `@4x` * `@5x` ## Template Image Template images consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance. The most common case is to use template images for a menu bar icon, so it can adapt to both light and dark menu bars. **Note:** Template image is only supported on macOS. To mark an image as a template image, its filename should end with the word `Template`. For example: * `xxxTemplate.png` * `[email protected]` ## Methods The `nativeImage` module has the following methods, all of which return an instance of the `NativeImage` class: ### `nativeImage.createEmpty()` Returns `NativeImage` Creates an empty `NativeImage` instance. ### `nativeImage.createThumbnailFromPath(path, maxSize)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `maxSize` [Size](structures/size.md) - the maximum width and height (positive numbers) the thumbnail returned can be. The Windows implementation will ignore `maxSize.height` and scale the height according to `maxSize.width`. Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). ### `nativeImage.createFromPath(path)` * `path` string Returns `NativeImage` Creates a new `NativeImage` instance from a file located at `path`. This method returns an empty image if the `path` does not exist, cannot be read, or is not a valid image. ```javascript const nativeImage = require('electron').nativeImage const image = nativeImage.createFromPath('/Users/somebody/images/icon.png') console.log(image) ``` ### `nativeImage.createFromBitmap(buffer, options)` * `buffer` [Buffer][buffer] * `options` Object * `width` Integer * `height` Integer * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap pixel data returned by `toBitmap()`. The specific format is platform-dependent. ### `nativeImage.createFromBuffer(buffer[, options])` * `buffer` [Buffer][buffer] * `options` Object (optional) * `width` Integer (optional) - Required for bitmap buffers. * `height` Integer (optional) - Required for bitmap buffers. * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or JPEG first. ### `nativeImage.createFromDataURL(dataURL)` * `dataURL` string Returns `NativeImage` Creates a new `NativeImage` instance from `dataURL`. ### `nativeImage.createFromNamedImage(imageName[, hslShift])` _macOS_ * `imageName` string * `hslShift` number[] (optional) Returns `NativeImage` Creates a new `NativeImage` instance from the NSImage that maps to the given image name. See [`System Icons`](https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/system-icons/) for a list of possible values. The `hslShift` is applied to the image with the following rules: * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0 and 360 on the hue color wheel (red). * `hsl_shift[1]` (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image. * `hsl_shift[2]` (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white). This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1, 0]` will make the image completely black. In some cases, the `NSImageName` doesn't match its string representation; one example of this is `NSFolderImageName`, whose string representation would actually be `NSFolder`. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following: `echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test` where `SYSTEM_IMAGE_NAME` should be replaced with any value from [this list](https://developer.apple.com/documentation/appkit/nsimagename?language=objc). ## Class: NativeImage > Natively wrap images such as tray, dock, and application icons. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-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 Methods The following methods are available on instances of the `NativeImage` class: #### `image.toPNG([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data. #### `image.toJPEG(quality)` * `quality` Integer - Between 0 - 100. Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data. #### `image.toBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel data. #### `image.toDataURL([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `string` - The data URL of the image. #### `image.getBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's raw bitmap pixel data. The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does not copy the bitmap data, so you have to use the returned Buffer immediately in current event loop tick; otherwise the data might be changed or destroyed. #### `image.getNativeHandle()` _macOS_ Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of the image. On macOS, a pointer to `NSImage` instance would be returned. Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. #### `image.isEmpty()` Returns `boolean` - Whether the image is empty. #### `image.getSize([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns [`Size`](structures/size.md). If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value. #### `image.setTemplateImage(option)` * `option` boolean Marks the image as a template image. #### `image.isTemplateImage()` Returns `boolean` - Whether the image is a template image. #### `image.crop(rect)` * `rect` [Rectangle](structures/rectangle.md) - The area of the image to crop. Returns `NativeImage` - The cropped image. #### `image.resize(options)` * `options` Object * `width` Integer (optional) - Defaults to the image's width. * `height` Integer (optional) - Defaults to the image's height. * `quality` string (optional) - The desired quality of the resize image. Possible values are `good`, `better`, or `best`. The default is `best`. These values express a desired quality/speed tradeoff. They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. It is possible for all three methods to be mapped to the same algorithm on a given platform. Returns `NativeImage` - The resized image. If only the `height` or the `width` are specified then the current aspect ratio will be preserved in the resized image. #### `image.getAspectRatio([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Number` - The image's aspect ratio. If `scaleFactor` is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value. #### `image.getScaleFactors()` Returns `Number[]` - An array of all scale factors corresponding to representations for a given nativeImage. #### `image.addRepresentation(options)` * `options` Object * `scaleFactor` Number (optional) - The scale factor to add the image representation for. * `width` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `height` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `buffer` Buffer (optional) - The buffer containing the raw image data. * `dataURL` string (optional) - The data URL containing either a base 64 encoded PNG or JPEG image. Add an image representation for a specific scale factor. This can be used to explicitly add different scale factor representations to an image. This can be called on empty images. [buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer ### Instance Properties #### `nativeImage.isMacTemplateImage` _macOS_ A `boolean` property that determines whether the image is considered a [template image](https://developer.apple.com/documentation/appkit/nsimage/1520017-template). Please note that this property only has an effect on macOS.
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (24.0) ### Deprecated: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Removed in Electron 24 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Deprecated: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been deprecated, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Removed in Electron 24 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ## Planned Breaking API Changes (23.0) ### Behavior Changed: Draggable Regions on macOS The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable. Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion). As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23. ### Removed: Windows 7 / 8 / 8.1 support [Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en). Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher. ### Removed: BrowserWindow `scroll-touch-*` events The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow have been removed. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Removed in Electron 23.0 win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)` The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)` The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ## Planned Breaking API Changes (22.0) ### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)` `webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)` `webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: WebContents `new-window` event The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Removed in Electron 22 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow are deprecated. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Deprecated win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ## Planned Breaking API Changes (21.0) ### Behavior Changed: V8 Memory Cage enabled The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with `ArrayBuffer` or `Buffer`. See the [blog post about the V8 memory cage](https://www.electronjs.org/blog/v8-memory-cage) for more details. ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).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) }) ``` ## Planned Breaking API Changes (20.0) ### Removed: macOS 10.11 / 10.12 support macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050). Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher. ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame [`WebFrameMain`](api/web-frame-main.md), but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) ### Removed: IA32 Linux binaries This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the [removal of support for IA32 Linux](#removed-ia32-linux-support). ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](./tutorial/using-native-node-modules.md) for more. ### Removed: IA32 Linux support Electron 18 will no longer run on 32-bit Linux systems. See [discontinuing support for 32-bit Linux](https://www.electronjs.org/blog/linux-32bit-support) for more information. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
shell/common/api/electron_api_native_image_win.cc
// Copyright (c) 2020 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_native_image.h" #include <windows.h> #include <thumbcache.h> #include <wrl/client.h> #include "base/win/scoped_com_initializer.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/skia_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/icon_util.h" #include "ui/gfx/image/image_skia.h" namespace electron::api { // static v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( v8::Isolate* isolate, const base::FilePath& path, const gfx::Size& size) { base::win::ScopedCOMInitializer scoped_com_initializer; gin_helper::Promise<gfx::Image> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); HRESULT hr; if (size.IsEmpty()) { promise.RejectWithErrorMessage("size must not be empty"); return handle; } // create an IShellItem Microsoft::WRL::ComPtr<IShellItem> pItem; std::wstring image_path = path.value(); hr = SHCreateItemFromParsingName(image_path.c_str(), nullptr, IID_PPV_ARGS(&pItem)); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to create IShellItem from the given path"); return handle; } // Init thumbnail cache Microsoft::WRL::ComPtr<IThumbnailCache> pThumbnailCache; hr = CoCreateInstance(CLSID_LocalThumbnailCache, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&pThumbnailCache)); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to acquire local thumbnail cache reference"); return handle; } // Populate the IShellBitmap Microsoft::WRL::ComPtr<ISharedBitmap> pThumbnail; WTS_CACHEFLAGS flags; WTS_THUMBNAILID thumbId; hr = pThumbnailCache->GetThumbnail(pItem.Get(), size.width(), WTS_FLAGS::WTS_NONE, &pThumbnail, &flags, &thumbId); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to get thumbnail from local thumbnail cache reference"); return handle; } // Init HBITMAP HBITMAP hBitmap = NULL; hr = pThumbnail->GetSharedBitmap(&hBitmap); if (FAILED(hr)) { promise.RejectWithErrorMessage("failed to extract bitmap from thumbnail"); return handle; } // convert HBITMAP to gfx::Image BITMAP bitmap; if (!GetObject(hBitmap, sizeof(bitmap), &bitmap)) { promise.RejectWithErrorMessage("could not convert HBITMAP to BITMAP"); return handle; } ICONINFO icon_info; icon_info.fIcon = TRUE; icon_info.hbmMask = hBitmap; icon_info.hbmColor = hBitmap; base::win::ScopedHICON icon(CreateIconIndirect(&icon_info)); SkBitmap skbitmap = IconUtil::CreateSkBitmapFromHICON(icon.get()); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFromBitmap(skbitmap, 1.0 /*scale factor*/); gfx::Image gfx_image = gfx::Image(image_skia); promise.Resolve(gfx_image); return handle; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
spec/api-native-image-spec.ts
import { expect } from 'chai'; import { nativeImage } from 'electron/common'; import { ifdescribe, ifit } from './lib/spec-helpers'; import * as path from 'path'; describe('nativeImage module', () => { const fixturesPath = path.join(__dirname, 'fixtures'); const imageLogo = { path: path.join(fixturesPath, 'assets', 'logo.png'), width: 538, height: 190 }; const image1x1 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYlWNgAAIAAAUAAdafFs0AAAAASUVORK5CYII=', path: path.join(fixturesPath, 'assets', '1x1.png'), height: 1, width: 1 }; const image2x2 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==', path: path.join(fixturesPath, 'assets', '2x2.jpg'), height: 2, width: 2 }; const image3x3 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAADElEQVQYlWNgIAoAAAAnAAGZWEMnAAAAAElFTkSuQmCC', path: path.join(fixturesPath, 'assets', '3x3.png'), height: 3, width: 3 }; const dataUrlImages = [ image1x1, image2x2, image3x3 ]; ifdescribe(process.platform === 'darwin')('isMacTemplateImage state', () => { describe('with properties', () => { it('correctly recognizes a template image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isMacTemplateImage).to.be.false(); const templateImage = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo_Template.png')); expect(templateImage.isMacTemplateImage).to.be.true(); }); it('sets a template image', function () { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isMacTemplateImage).to.be.false(); image.isMacTemplateImage = true; expect(image.isMacTemplateImage).to.be.true(); }); }); describe('with functions', () => { it('correctly recognizes a template image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isTemplateImage()).to.be.false(); const templateImage = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo_Template.png')); expect(templateImage.isTemplateImage()).to.be.true(); }); it('sets a template image', function () { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isTemplateImage()).to.be.false(); image.setTemplateImage(true); expect(image.isTemplateImage()).to.be.true(); }); }); }); describe('createEmpty()', () => { it('returns an empty image', () => { const empty = nativeImage.createEmpty(); expect(empty.isEmpty()).to.be.true(); expect(empty.getAspectRatio()).to.equal(1); expect(empty.toDataURL()).to.equal('data:image/png;base64,'); expect(empty.toDataURL({ scaleFactor: 2.0 })).to.equal('data:image/png;base64,'); expect(empty.getSize()).to.deep.equal({ width: 0, height: 0 }); expect(empty.getBitmap()).to.be.empty(); expect(empty.getBitmap({ scaleFactor: 2.0 })).to.be.empty(); expect(empty.toBitmap()).to.be.empty(); expect(empty.toBitmap({ scaleFactor: 2.0 })).to.be.empty(); expect(empty.toJPEG(100)).to.be.empty(); expect(empty.toPNG()).to.be.empty(); expect(empty.toPNG({ scaleFactor: 2.0 })).to.be.empty(); if (process.platform === 'darwin') { expect(empty.getNativeHandle()).to.be.empty(); } }); }); describe('createFromBitmap(buffer, options)', () => { it('returns an empty image when the buffer is empty', () => { expect(nativeImage.createFromBitmap(Buffer.from([]), { width: 0, height: 0 }).isEmpty()).to.be.true(); }); it('returns an image created from the given buffer', () => { const imageA = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const imageB = nativeImage.createFromBitmap(imageA.toBitmap(), imageA.getSize()); expect(imageB.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageC = nativeImage.createFromBuffer(imageA.toBitmap(), { ...imageA.getSize(), scaleFactor: 2.0 }); expect(imageC.getSize()).to.deep.equal({ width: 269, height: 95 }); }); it('throws on invalid arguments', () => { expect(() => nativeImage.createFromBitmap(null as any, {} as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBitmap([12, 14, 124, 12] as any, {} as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), {} as any)).to.throw('width is required'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), { width: 1 } as any)).to.throw('height is required'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), { width: 1, height: 1 })).to.throw('invalid buffer size'); }); }); describe('createFromBuffer(buffer, options)', () => { it('returns an empty image when the buffer is empty', () => { expect(nativeImage.createFromBuffer(Buffer.from([])).isEmpty()).to.be.true(); }); it('returns an empty image when the buffer is too small', () => { const image = nativeImage.createFromBuffer(Buffer.from([1, 2, 3, 4]), { width: 100, height: 100 }); expect(image.isEmpty()).to.be.true(); }); it('returns an image created from the given buffer', () => { const imageA = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const imageB = nativeImage.createFromBuffer(imageA.toPNG()); expect(imageB.getSize()).to.deep.equal({ width: 538, height: 190 }); expect(imageA.toBitmap().equals(imageB.toBitmap())).to.be.true(); const imageC = nativeImage.createFromBuffer(imageA.toJPEG(100)); expect(imageC.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageD = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 538, height: 190 }); expect(imageD.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageE = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 100, height: 200 }); expect(imageE.getSize()).to.deep.equal({ width: 100, height: 200 }); const imageF = nativeImage.createFromBuffer(imageA.toBitmap()); expect(imageF.isEmpty()).to.be.true(); const imageG = nativeImage.createFromBuffer(imageA.toPNG(), { width: 100, height: 200 }); expect(imageG.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageH = nativeImage.createFromBuffer(imageA.toJPEG(100), { width: 100, height: 200 }); expect(imageH.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageI = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 538, height: 190, scaleFactor: 2.0 }); expect(imageI.getSize()).to.deep.equal({ width: 269, height: 95 }); }); it('throws on invalid arguments', () => { expect(() => nativeImage.createFromBuffer(null as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBuffer([12, 14, 124, 12] as any)).to.throw('buffer must be a node Buffer'); }); }); describe('createFromDataURL(dataURL)', () => { it('returns an empty image from the empty string', () => { expect(nativeImage.createFromDataURL('').isEmpty()).to.be.true(); }); it('returns an image created from the given string', () => { for (const imageData of dataUrlImages) { const imageFromPath = nativeImage.createFromPath(imageData.path); const imageFromDataUrl = nativeImage.createFromDataURL(imageData.dataUrl!); expect(imageFromDataUrl.isEmpty()).to.be.false(); expect(imageFromDataUrl.getSize()).to.deep.equal(imageFromPath.getSize()); expect(imageFromDataUrl.toBitmap()).to.satisfy( (bitmap: any) => imageFromPath.toBitmap().equals(bitmap)); expect(imageFromDataUrl.toDataURL()).to.equal(imageFromPath.toDataURL()); } }); }); describe('toDataURL()', () => { it('returns a PNG data URL', () => { for (const imageData of dataUrlImages) { const imageFromPath = nativeImage.createFromPath(imageData.path!); const scaleFactors = [1.0, 2.0]; for (const scaleFactor of scaleFactors) { expect(imageFromPath.toDataURL({ scaleFactor })).to.equal(imageData.dataUrl); } } }); it('returns a data URL at 1x scale factor by default', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const imageOne = nativeImage.createFromBuffer(image.toPNG(), { width: image.getSize().width, height: image.getSize().height, scaleFactor: 2.0 }); expect(imageOne.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); const imageTwo = nativeImage.createFromDataURL(imageOne.toDataURL()); expect(imageTwo.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); expect(imageOne.toBitmap().equals(imageTwo.toBitmap())).to.be.true(); }); it('supports a scale factor', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const expectedSize = { width: imageData.width, height: imageData.height }; const imageFromDataUrlOne = nativeImage.createFromDataURL( image.toDataURL({ scaleFactor: 1.0 })); expect(imageFromDataUrlOne.getSize()).to.deep.equal(expectedSize); const imageFromDataUrlTwo = nativeImage.createFromDataURL( image.toDataURL({ scaleFactor: 2.0 })); expect(imageFromDataUrlTwo.getSize()).to.deep.equal(expectedSize); }); }); describe('toPNG()', () => { it('returns a buffer at 1x scale factor by default', () => { const imageData = imageLogo; const imageA = nativeImage.createFromPath(imageData.path); const imageB = nativeImage.createFromBuffer(imageA.toPNG(), { width: imageA.getSize().width, height: imageA.getSize().height, scaleFactor: 2.0 }); expect(imageB.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); const imageC = nativeImage.createFromBuffer(imageB.toPNG()); expect(imageC.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); expect(imageB.toBitmap().equals(imageC.toBitmap())).to.be.true(); }); it('supports a scale factor', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const imageFromBufferOne = nativeImage.createFromBuffer( image.toPNG({ scaleFactor: 1.0 })); expect(imageFromBufferOne.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); const imageFromBufferTwo = nativeImage.createFromBuffer( image.toPNG({ scaleFactor: 2.0 }), { scaleFactor: 2.0 }); expect(imageFromBufferTwo.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); }); }); describe('createFromPath(path)', () => { it('returns an empty image for invalid paths', () => { expect(nativeImage.createFromPath('').isEmpty()).to.be.true(); expect(nativeImage.createFromPath('does-not-exist.png').isEmpty()).to.be.true(); expect(nativeImage.createFromPath('does-not-exist.ico').isEmpty()).to.be.true(); expect(nativeImage.createFromPath(__dirname).isEmpty()).to.be.true(); expect(nativeImage.createFromPath(__filename).isEmpty()).to.be.true(); }); it('loads images from paths relative to the current working directory', () => { const imagePath = path.relative('.', path.join(fixturesPath, 'assets', 'logo.png')); const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); it('loads images from paths with `.` segments', () => { const imagePath = `${path.join(fixturesPath)}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); it('loads images from paths with `..` segments', () => { const imagePath = `${path.join(fixturesPath, 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); ifit(process.platform === 'darwin')('Gets an NSImage pointer on macOS', function () { const imagePath = `${path.join(fixturesPath, 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); const nsimage = image.getNativeHandle(); expect(nsimage).to.have.lengthOf(8); // If all bytes are null, that's Bad const allBytesAreNotNull = nsimage.reduce((acc, x) => acc || (x !== 0), false); expect(allBytesAreNotNull); }); ifit(process.platform === 'win32')('loads images from .ico files on Windows', function () { const imagePath = path.join(fixturesPath, 'assets', 'icon.ico'); const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 256, height: 256 }); }); }); describe('createFromNamedImage(name)', () => { it('returns empty for invalid options', () => { const image = nativeImage.createFromNamedImage('totally_not_real'); expect(image.isEmpty()).to.be.true(); }); ifit(process.platform !== 'darwin')('returns empty on non-darwin platforms', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate'); expect(image.isEmpty()).to.be.true(); }); ifit(process.platform === 'darwin')('returns a valid image on darwin', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate'); expect(image.isEmpty()).to.be.false(); }); ifit(process.platform === 'darwin')('returns allows an HSL shift for a valid image on darwin', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate', [0.5, 0.2, 0.8]); expect(image.isEmpty()).to.be.false(); }); }); describe('resize(options)', () => { it('returns a resized image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); for (const [resizeTo, expectedSize] of new Map([ [{}, { width: 538, height: 190 }], [{ width: 269 }, { width: 269, height: 95 }], [{ width: 600 }, { width: 600, height: 212 }], [{ height: 95 }, { width: 269, height: 95 }], [{ height: 200 }, { width: 566, height: 200 }], [{ width: 80, height: 65 }, { width: 80, height: 65 }], [{ width: 600, height: 200 }, { width: 600, height: 200 }], [{ width: 0, height: 0 }, { width: 0, height: 0 }], [{ width: -1, height: -1 }, { width: 0, height: 0 }] ])) { const actualSize = image.resize(resizeTo).getSize(); expect(actualSize).to.deep.equal(expectedSize); } }); it('returns an empty image when called on an empty image', () => { expect(nativeImage.createEmpty().resize({ width: 1, height: 1 }).isEmpty()).to.be.true(); expect(nativeImage.createEmpty().resize({ width: 0, height: 0 }).isEmpty()).to.be.true(); }); it('supports a quality option', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const good = image.resize({ width: 100, height: 100, quality: 'good' }); const better = image.resize({ width: 100, height: 100, quality: 'better' }); const best = image.resize({ width: 100, height: 100, quality: 'best' }); expect(good.toPNG()).to.have.lengthOf.at.most(better.toPNG().length); expect(better.toPNG()).to.have.lengthOf.below(best.toPNG().length); }); }); describe('crop(bounds)', () => { it('returns an empty image when called on an empty image', () => { expect(nativeImage.createEmpty().crop({ width: 1, height: 2, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(nativeImage.createEmpty().crop({ width: 0, height: 0, x: 0, y: 0 }).isEmpty()).to.be.true(); }); it('returns an empty image when the bounds are invalid', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.crop({ width: 0, height: 0, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: -1, height: 10, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: 10, height: -35, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: 100, height: 100, x: 1000, y: 1000 }).isEmpty()).to.be.true(); }); it('returns a cropped image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const cropA = image.crop({ width: 25, height: 64, x: 0, y: 0 }); const cropB = image.crop({ width: 25, height: 64, x: 30, y: 40 }); expect(cropA.getSize()).to.deep.equal({ width: 25, height: 64 }); expect(cropB.getSize()).to.deep.equal({ width: 25, height: 64 }); expect(cropA.toPNG().equals(cropB.toPNG())).to.be.false(); }); it('toBitmap() returns a buffer of the right size', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const crop = image.crop({ width: 25, height: 64, x: 0, y: 0 }); expect(crop.toBitmap().length).to.equal(25 * 64 * 4); }); }); describe('getAspectRatio()', () => { it('returns an aspect ratio of an empty image', () => { expect(nativeImage.createEmpty().getAspectRatio()).to.equal(1.0); }); it('returns an aspect ratio of an image', () => { const imageData = imageLogo; // imageData.width / imageData.height = 2.831578947368421 const expectedAspectRatio = 2.8315789699554443; const image = nativeImage.createFromPath(imageData.path); expect(image.getAspectRatio()).to.equal(expectedAspectRatio); }); }); ifdescribe(process.platform !== 'linux')('createThumbnailFromPath(path, size)', () => { it('throws when invalid size is passed', async () => { const badSize = { width: -1, height: -1 }; await expect( nativeImage.createThumbnailFromPath('path', badSize) ).to.eventually.be.rejectedWith('size must not be empty'); }); it('throws when a bad path is passed', async () => { const badPath = process.platform === 'win32' ? '\\hey\\hi\\hello' : '/hey/hi/hello'; const goodSize = { width: 100, height: 100 }; await expect( nativeImage.createThumbnailFromPath(badPath, goodSize) ).to.eventually.be.rejected(); }); it('returns native image given valid params', async () => { const goodPath = path.join(fixturesPath, 'assets', 'logo.png'); const goodSize = { width: 100, height: 100 }; const result = await nativeImage.createThumbnailFromPath(goodPath, goodSize); expect(result.isEmpty()).to.equal(false); }); }); describe('addRepresentation()', () => { it('does not add representation when the buffer is too small', () => { const image = nativeImage.createEmpty(); image.addRepresentation({ buffer: Buffer.from([1, 2, 3, 4]), width: 100, height: 100 }); expect(image.isEmpty()).to.be.true(); }); it('supports adding a buffer representation for a scale factor', () => { const image = nativeImage.createEmpty(); const imageDataOne = image1x1; image.addRepresentation({ scaleFactor: 1.0, buffer: nativeImage.createFromPath(imageDataOne.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1]); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, buffer: nativeImage.createFromPath(imageDataTwo.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1, 2]); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 3.0, buffer: nativeImage.createFromPath(imageDataThree.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1, 2, 3]); image.addRepresentation({ scaleFactor: 4.0, buffer: 'invalid' as any }); // this one failed, so it shouldn't show up in the scale factors expect(image.getScaleFactors()).to.deep.equal([1, 2, 3]); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 1, height: 1 }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); expect(image.toDataURL({ scaleFactor: 3.0 })).to.equal(imageDataThree.dataUrl); expect(image.toDataURL({ scaleFactor: 4.0 })).to.equal(imageDataThree.dataUrl); }); it('supports adding a data URL representation for a scale factor', () => { const image = nativeImage.createEmpty(); const imageDataOne = image1x1; image.addRepresentation({ scaleFactor: 1.0, dataURL: imageDataOne.dataUrl }); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataTwo.dataUrl }); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 3.0, dataURL: imageDataThree.dataUrl }); image.addRepresentation({ scaleFactor: 4.0, dataURL: 'invalid' }); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 1, height: 1 }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); expect(image.toDataURL({ scaleFactor: 3.0 })).to.equal(imageDataThree.dataUrl); expect(image.toDataURL({ scaleFactor: 4.0 })).to.equal(imageDataThree.dataUrl); }); it('supports adding a representation to an existing image', () => { const imageDataOne = image1x1; const image = nativeImage.createFromPath(imageDataOne.path); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataTwo.dataUrl }); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataThree.dataUrl }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
spec/fixtures/assets/capybara.png
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
docs/api/native-image.md
# nativeImage > Create tray, dock, and application icons using PNG or JPG files. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) In Electron, for the APIs that take images, you can pass either file paths or `NativeImage` instances. An empty image will be used when `null` is passed. For example, when creating a tray or setting a window's icon, you can pass an image file path as a `string`: ```javascript const { BrowserWindow, Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }) console.log(appIcon, win) ``` Or read the image from the clipboard, which returns a `NativeImage`: ```javascript const { clipboard, Tray } = require('electron') const image = clipboard.readImage() const appIcon = new Tray(image) console.log(appIcon) ``` ## Supported Formats Currently `PNG` and `JPEG` image formats are supported. `PNG` is recommended because of its support for transparency and lossless compression. On Windows, you can also load `ICO` icons from file paths. For best visual quality, it is recommended to include at least the following sizes in the: * Small icon * 16x16 (100% DPI scale) * 20x20 (125% DPI scale) * 24x24 (150% DPI scale) * 32x32 (200% DPI scale) * Large icon * 32x32 (100% DPI scale) * 40x40 (125% DPI scale) * 48x48 (150% DPI scale) * 64x64 (200% DPI scale) * 256x256 Check the *Size requirements* section in [this article][icons]. [icons]:https://msdn.microsoft.com/en-us/library/windows/desktop/dn742485(v=vs.85).aspx ## High Resolution Image On platforms that have high-DPI support such as Apple Retina displays, you can append `@2x` after image's base filename to mark it as a high resolution image. For example, if `icon.png` is a normal image that has standard resolution, then `[email protected]` will be treated as a high resolution image that has double DPI density. If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes. For example: ```plaintext images/ ├── icon.png ├── [email protected] └── [email protected] ``` ```javascript const { Tray } = require('electron') const appIcon = new Tray('/Users/somebody/images/icon.png') console.log(appIcon) ``` The following suffixes for DPI are also supported: * `@1x` * `@1.25x` * `@1.33x` * `@1.4x` * `@1.5x` * `@1.8x` * `@2x` * `@2.5x` * `@3x` * `@4x` * `@5x` ## Template Image Template images consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance. The most common case is to use template images for a menu bar icon, so it can adapt to both light and dark menu bars. **Note:** Template image is only supported on macOS. To mark an image as a template image, its filename should end with the word `Template`. For example: * `xxxTemplate.png` * `[email protected]` ## Methods The `nativeImage` module has the following methods, all of which return an instance of the `NativeImage` class: ### `nativeImage.createEmpty()` Returns `NativeImage` Creates an empty `NativeImage` instance. ### `nativeImage.createThumbnailFromPath(path, maxSize)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `maxSize` [Size](structures/size.md) - the maximum width and height (positive numbers) the thumbnail returned can be. The Windows implementation will ignore `maxSize.height` and scale the height according to `maxSize.width`. Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). ### `nativeImage.createFromPath(path)` * `path` string Returns `NativeImage` Creates a new `NativeImage` instance from a file located at `path`. This method returns an empty image if the `path` does not exist, cannot be read, or is not a valid image. ```javascript const nativeImage = require('electron').nativeImage const image = nativeImage.createFromPath('/Users/somebody/images/icon.png') console.log(image) ``` ### `nativeImage.createFromBitmap(buffer, options)` * `buffer` [Buffer][buffer] * `options` Object * `width` Integer * `height` Integer * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap pixel data returned by `toBitmap()`. The specific format is platform-dependent. ### `nativeImage.createFromBuffer(buffer[, options])` * `buffer` [Buffer][buffer] * `options` Object (optional) * `width` Integer (optional) - Required for bitmap buffers. * `height` Integer (optional) - Required for bitmap buffers. * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or JPEG first. ### `nativeImage.createFromDataURL(dataURL)` * `dataURL` string Returns `NativeImage` Creates a new `NativeImage` instance from `dataURL`. ### `nativeImage.createFromNamedImage(imageName[, hslShift])` _macOS_ * `imageName` string * `hslShift` number[] (optional) Returns `NativeImage` Creates a new `NativeImage` instance from the NSImage that maps to the given image name. See [`System Icons`](https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/system-icons/) for a list of possible values. The `hslShift` is applied to the image with the following rules: * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0 and 360 on the hue color wheel (red). * `hsl_shift[1]` (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image. * `hsl_shift[2]` (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white). This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1, 0]` will make the image completely black. In some cases, the `NSImageName` doesn't match its string representation; one example of this is `NSFolderImageName`, whose string representation would actually be `NSFolder`. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following: `echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test` where `SYSTEM_IMAGE_NAME` should be replaced with any value from [this list](https://developer.apple.com/documentation/appkit/nsimagename?language=objc). ## Class: NativeImage > Natively wrap images such as tray, dock, and application icons. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-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 Methods The following methods are available on instances of the `NativeImage` class: #### `image.toPNG([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data. #### `image.toJPEG(quality)` * `quality` Integer - Between 0 - 100. Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data. #### `image.toBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel data. #### `image.toDataURL([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `string` - The data URL of the image. #### `image.getBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's raw bitmap pixel data. The difference between `getBitmap()` and `toBitmap()` is that `getBitmap()` does not copy the bitmap data, so you have to use the returned Buffer immediately in current event loop tick; otherwise the data might be changed or destroyed. #### `image.getNativeHandle()` _macOS_ Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of the image. On macOS, a pointer to `NSImage` instance would be returned. Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. #### `image.isEmpty()` Returns `boolean` - Whether the image is empty. #### `image.getSize([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns [`Size`](structures/size.md). If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value. #### `image.setTemplateImage(option)` * `option` boolean Marks the image as a template image. #### `image.isTemplateImage()` Returns `boolean` - Whether the image is a template image. #### `image.crop(rect)` * `rect` [Rectangle](structures/rectangle.md) - The area of the image to crop. Returns `NativeImage` - The cropped image. #### `image.resize(options)` * `options` Object * `width` Integer (optional) - Defaults to the image's width. * `height` Integer (optional) - Defaults to the image's height. * `quality` string (optional) - The desired quality of the resize image. Possible values are `good`, `better`, or `best`. The default is `best`. These values express a desired quality/speed tradeoff. They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. It is possible for all three methods to be mapped to the same algorithm on a given platform. Returns `NativeImage` - The resized image. If only the `height` or the `width` are specified then the current aspect ratio will be preserved in the resized image. #### `image.getAspectRatio([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Number` - The image's aspect ratio. If `scaleFactor` is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value. #### `image.getScaleFactors()` Returns `Number[]` - An array of all scale factors corresponding to representations for a given nativeImage. #### `image.addRepresentation(options)` * `options` Object * `scaleFactor` Number (optional) - The scale factor to add the image representation for. * `width` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `height` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `buffer` Buffer (optional) - The buffer containing the raw image data. * `dataURL` string (optional) - The data URL containing either a base 64 encoded PNG or JPEG image. Add an image representation for a specific scale factor. This can be used to explicitly add different scale factor representations to an image. This can be called on empty images. [buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer ### Instance Properties #### `nativeImage.isMacTemplateImage` _macOS_ A `boolean` property that determines whether the image is considered a [template image](https://developer.apple.com/documentation/appkit/nsimage/1520017-template). Please note that this property only has an effect on macOS.
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (24.0) ### Deprecated: `BrowserWindow.setTrafficLightPosition(position)` `BrowserWindow.setTrafficLightPosition(position)` has been deprecated, the `BrowserWindow.setWindowButtonPosition(position)` API should be used instead which accepts `null` instead of `{ x: 0, y: 0 }` to reset the position to system default. ```js // Removed in Electron 24 win.setTrafficLightPosition({ x: 10, y: 10 }) win.setTrafficLightPosition({ x: 0, y: 0 }) // Replace with win.setWindowButtonPosition({ x: 10, y: 10 }) win.setWindowButtonPosition(null) ``` ### Deprecated: `BrowserWindow.getTrafficLightPosition()` `BrowserWindow.getTrafficLightPosition()` has been deprecated, the `BrowserWindow.getWindowButtonPosition()` API should be used instead which returns `null` instead of `{ x: 0, y: 0 }` when there is no custom position. ```js // Removed in Electron 24 const pos = win.getTrafficLightPosition() if (pos.x === 0 && pos.y === 0) { // No custom position. } // Replace with const ret = win.getWindowButtonPosition() if (ret === null) { // No custom position. } ``` ## Planned Breaking API Changes (23.0) ### Behavior Changed: Draggable Regions on macOS The implementation of draggable regions (using the CSS property `-webkit-app-region: drag`) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with `-webkit-app-region: no-drag` overlapped a region with `-webkit-app-region: drag`, the `no-drag` region would always take precedence on macOS, regardless of CSS layering. That is, if a `drag` region was above a `no-drag` region, it would be ignored. Beginning in Electron 23, a `drag` region on top of a `no-drag` region will correctly cause the region to be draggable. Additionally, the `customButtonsOnHover` BrowserWindow property previously created a draggable region which ignored the `-webkit-app-region` CSS property. This has now been fixed (see [#37210](https://github.com/electron/electron/issues/37210#issuecomment-1440509592) for discussion). As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23. ### Removed: Windows 7 / 8 / 8.1 support [Windows 7, Windows 8, and Windows 8.1 are no longer supported](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice). Electron follows the planned Chromium deprecation policy, which will [deprecate Windows 7 support beginning in Chromium 109](https://support.google.com/chrome/thread/185534985/sunsetting-support-for-windows-7-8-8-1-in-early-2023?hl=en). Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher. ### Removed: BrowserWindow `scroll-touch-*` events The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow have been removed. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Removed in Electron 23.0 win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ### Removed: `webContents.incrementCapturerCount(stayHidden, stayAwake)` The `webContents.incrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: `webContents.decrementCapturerCount(stayHidden, stayAwake)` The `webContents.decrementCapturerCount(stayHidden, stayAwake)` function has been removed. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ## Planned Breaking API Changes (22.0) ### Deprecated: `webContents.incrementCapturerCount(stayHidden, stayAwake)` `webContents.incrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Deprecated: `webContents.decrementCapturerCount(stayHidden, stayAwake)` `webContents.decrementCapturerCount(stayHidden, stayAwake)` has been deprecated. It is now automatically handled by `webContents.capturePage` when a page capture completes. ```js const w = new BrowserWindow({ show: false }) // Removed in Electron 23 w.webContents.incrementCapturerCount() w.capturePage().then(image => { console.log(image.toDataURL()) w.webContents.decrementCapturerCount() }) // Replace with w.capturePage().then(image => { console.log(image.toDataURL()) }) ``` ### Removed: WebContents `new-window` event The `new-window` event of WebContents has been removed. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Removed in Electron 22 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ### Deprecated: BrowserWindow `scroll-touch-*` events The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on BrowserWindow are deprecated. Instead, use the newly available [`input-event` event](api/web-contents.md#event-input-event) on WebContents. ```js // Deprecated win.on('scroll-touch-begin', scrollTouchBegin) win.on('scroll-touch-edge', scrollTouchEdge) win.on('scroll-touch-end', scrollTouchEnd) // Replace with win.webContents.on('input-event', (_, event) => { if (event.type === 'gestureScrollBegin') { scrollTouchBegin() } else if (event.type === 'gestureScrollUpdate') { scrollTouchEdge() } else if (event.type === 'gestureScrollEnd') { scrollTouchEnd() } }) ``` ## Planned Breaking API Changes (21.0) ### Behavior Changed: V8 Memory Cage enabled The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with `ArrayBuffer` or `Buffer`. See the [blog post about the V8 memory cage](https://www.electronjs.org/blog/v8-memory-cage) for more details. ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).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) }) ``` ## Planned Breaking API Changes (20.0) ### Removed: macOS 10.11 / 10.12 support macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by [Chromium](https://chromium-review.googlesource.com/c/chromium/src/+/3646050). Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher. ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame [`WebFrameMain`](api/web-frame-main.md), but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) ### Removed: IA32 Linux binaries This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the [removal of support for IA32 Linux](#removed-ia32-linux-support). ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](./tutorial/using-native-node-modules.md) for more. ### Removed: IA32 Linux support Electron 18 will no longer run on 32-bit Linux systems. See [discontinuing support for 32-bit Linux](https://www.electronjs.org/blog/linux-32bit-support) for more information. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
shell/common/api/electron_api_native_image_win.cc
// Copyright (c) 2020 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_native_image.h" #include <windows.h> #include <thumbcache.h> #include <wrl/client.h> #include "base/win/scoped_com_initializer.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/promise.h" #include "shell/common/skia_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/icon_util.h" #include "ui/gfx/image/image_skia.h" namespace electron::api { // static v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( v8::Isolate* isolate, const base::FilePath& path, const gfx::Size& size) { base::win::ScopedCOMInitializer scoped_com_initializer; gin_helper::Promise<gfx::Image> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); HRESULT hr; if (size.IsEmpty()) { promise.RejectWithErrorMessage("size must not be empty"); return handle; } // create an IShellItem Microsoft::WRL::ComPtr<IShellItem> pItem; std::wstring image_path = path.value(); hr = SHCreateItemFromParsingName(image_path.c_str(), nullptr, IID_PPV_ARGS(&pItem)); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to create IShellItem from the given path"); return handle; } // Init thumbnail cache Microsoft::WRL::ComPtr<IThumbnailCache> pThumbnailCache; hr = CoCreateInstance(CLSID_LocalThumbnailCache, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&pThumbnailCache)); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to acquire local thumbnail cache reference"); return handle; } // Populate the IShellBitmap Microsoft::WRL::ComPtr<ISharedBitmap> pThumbnail; WTS_CACHEFLAGS flags; WTS_THUMBNAILID thumbId; hr = pThumbnailCache->GetThumbnail(pItem.Get(), size.width(), WTS_FLAGS::WTS_NONE, &pThumbnail, &flags, &thumbId); if (FAILED(hr)) { promise.RejectWithErrorMessage( "failed to get thumbnail from local thumbnail cache reference"); return handle; } // Init HBITMAP HBITMAP hBitmap = NULL; hr = pThumbnail->GetSharedBitmap(&hBitmap); if (FAILED(hr)) { promise.RejectWithErrorMessage("failed to extract bitmap from thumbnail"); return handle; } // convert HBITMAP to gfx::Image BITMAP bitmap; if (!GetObject(hBitmap, sizeof(bitmap), &bitmap)) { promise.RejectWithErrorMessage("could not convert HBITMAP to BITMAP"); return handle; } ICONINFO icon_info; icon_info.fIcon = TRUE; icon_info.hbmMask = hBitmap; icon_info.hbmColor = hBitmap; base::win::ScopedHICON icon(CreateIconIndirect(&icon_info)); SkBitmap skbitmap = IconUtil::CreateSkBitmapFromHICON(icon.get()); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFromBitmap(skbitmap, 1.0 /*scale factor*/); gfx::Image gfx_image = gfx::Image(image_skia); promise.Resolve(gfx_image); return handle; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
spec/api-native-image-spec.ts
import { expect } from 'chai'; import { nativeImage } from 'electron/common'; import { ifdescribe, ifit } from './lib/spec-helpers'; import * as path from 'path'; describe('nativeImage module', () => { const fixturesPath = path.join(__dirname, 'fixtures'); const imageLogo = { path: path.join(fixturesPath, 'assets', 'logo.png'), width: 538, height: 190 }; const image1x1 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYlWNgAAIAAAUAAdafFs0AAAAASUVORK5CYII=', path: path.join(fixturesPath, 'assets', '1x1.png'), height: 1, width: 1 }; const image2x2 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==', path: path.join(fixturesPath, 'assets', '2x2.jpg'), height: 2, width: 2 }; const image3x3 = { dataUrl: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAADElEQVQYlWNgIAoAAAAnAAGZWEMnAAAAAElFTkSuQmCC', path: path.join(fixturesPath, 'assets', '3x3.png'), height: 3, width: 3 }; const dataUrlImages = [ image1x1, image2x2, image3x3 ]; ifdescribe(process.platform === 'darwin')('isMacTemplateImage state', () => { describe('with properties', () => { it('correctly recognizes a template image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isMacTemplateImage).to.be.false(); const templateImage = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo_Template.png')); expect(templateImage.isMacTemplateImage).to.be.true(); }); it('sets a template image', function () { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isMacTemplateImage).to.be.false(); image.isMacTemplateImage = true; expect(image.isMacTemplateImage).to.be.true(); }); }); describe('with functions', () => { it('correctly recognizes a template image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isTemplateImage()).to.be.false(); const templateImage = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo_Template.png')); expect(templateImage.isTemplateImage()).to.be.true(); }); it('sets a template image', function () { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.isTemplateImage()).to.be.false(); image.setTemplateImage(true); expect(image.isTemplateImage()).to.be.true(); }); }); }); describe('createEmpty()', () => { it('returns an empty image', () => { const empty = nativeImage.createEmpty(); expect(empty.isEmpty()).to.be.true(); expect(empty.getAspectRatio()).to.equal(1); expect(empty.toDataURL()).to.equal('data:image/png;base64,'); expect(empty.toDataURL({ scaleFactor: 2.0 })).to.equal('data:image/png;base64,'); expect(empty.getSize()).to.deep.equal({ width: 0, height: 0 }); expect(empty.getBitmap()).to.be.empty(); expect(empty.getBitmap({ scaleFactor: 2.0 })).to.be.empty(); expect(empty.toBitmap()).to.be.empty(); expect(empty.toBitmap({ scaleFactor: 2.0 })).to.be.empty(); expect(empty.toJPEG(100)).to.be.empty(); expect(empty.toPNG()).to.be.empty(); expect(empty.toPNG({ scaleFactor: 2.0 })).to.be.empty(); if (process.platform === 'darwin') { expect(empty.getNativeHandle()).to.be.empty(); } }); }); describe('createFromBitmap(buffer, options)', () => { it('returns an empty image when the buffer is empty', () => { expect(nativeImage.createFromBitmap(Buffer.from([]), { width: 0, height: 0 }).isEmpty()).to.be.true(); }); it('returns an image created from the given buffer', () => { const imageA = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const imageB = nativeImage.createFromBitmap(imageA.toBitmap(), imageA.getSize()); expect(imageB.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageC = nativeImage.createFromBuffer(imageA.toBitmap(), { ...imageA.getSize(), scaleFactor: 2.0 }); expect(imageC.getSize()).to.deep.equal({ width: 269, height: 95 }); }); it('throws on invalid arguments', () => { expect(() => nativeImage.createFromBitmap(null as any, {} as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBitmap([12, 14, 124, 12] as any, {} as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), {} as any)).to.throw('width is required'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), { width: 1 } as any)).to.throw('height is required'); expect(() => nativeImage.createFromBitmap(Buffer.from([]), { width: 1, height: 1 })).to.throw('invalid buffer size'); }); }); describe('createFromBuffer(buffer, options)', () => { it('returns an empty image when the buffer is empty', () => { expect(nativeImage.createFromBuffer(Buffer.from([])).isEmpty()).to.be.true(); }); it('returns an empty image when the buffer is too small', () => { const image = nativeImage.createFromBuffer(Buffer.from([1, 2, 3, 4]), { width: 100, height: 100 }); expect(image.isEmpty()).to.be.true(); }); it('returns an image created from the given buffer', () => { const imageA = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const imageB = nativeImage.createFromBuffer(imageA.toPNG()); expect(imageB.getSize()).to.deep.equal({ width: 538, height: 190 }); expect(imageA.toBitmap().equals(imageB.toBitmap())).to.be.true(); const imageC = nativeImage.createFromBuffer(imageA.toJPEG(100)); expect(imageC.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageD = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 538, height: 190 }); expect(imageD.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageE = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 100, height: 200 }); expect(imageE.getSize()).to.deep.equal({ width: 100, height: 200 }); const imageF = nativeImage.createFromBuffer(imageA.toBitmap()); expect(imageF.isEmpty()).to.be.true(); const imageG = nativeImage.createFromBuffer(imageA.toPNG(), { width: 100, height: 200 }); expect(imageG.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageH = nativeImage.createFromBuffer(imageA.toJPEG(100), { width: 100, height: 200 }); expect(imageH.getSize()).to.deep.equal({ width: 538, height: 190 }); const imageI = nativeImage.createFromBuffer(imageA.toBitmap(), { width: 538, height: 190, scaleFactor: 2.0 }); expect(imageI.getSize()).to.deep.equal({ width: 269, height: 95 }); }); it('throws on invalid arguments', () => { expect(() => nativeImage.createFromBuffer(null as any)).to.throw('buffer must be a node Buffer'); expect(() => nativeImage.createFromBuffer([12, 14, 124, 12] as any)).to.throw('buffer must be a node Buffer'); }); }); describe('createFromDataURL(dataURL)', () => { it('returns an empty image from the empty string', () => { expect(nativeImage.createFromDataURL('').isEmpty()).to.be.true(); }); it('returns an image created from the given string', () => { for (const imageData of dataUrlImages) { const imageFromPath = nativeImage.createFromPath(imageData.path); const imageFromDataUrl = nativeImage.createFromDataURL(imageData.dataUrl!); expect(imageFromDataUrl.isEmpty()).to.be.false(); expect(imageFromDataUrl.getSize()).to.deep.equal(imageFromPath.getSize()); expect(imageFromDataUrl.toBitmap()).to.satisfy( (bitmap: any) => imageFromPath.toBitmap().equals(bitmap)); expect(imageFromDataUrl.toDataURL()).to.equal(imageFromPath.toDataURL()); } }); }); describe('toDataURL()', () => { it('returns a PNG data URL', () => { for (const imageData of dataUrlImages) { const imageFromPath = nativeImage.createFromPath(imageData.path!); const scaleFactors = [1.0, 2.0]; for (const scaleFactor of scaleFactors) { expect(imageFromPath.toDataURL({ scaleFactor })).to.equal(imageData.dataUrl); } } }); it('returns a data URL at 1x scale factor by default', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const imageOne = nativeImage.createFromBuffer(image.toPNG(), { width: image.getSize().width, height: image.getSize().height, scaleFactor: 2.0 }); expect(imageOne.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); const imageTwo = nativeImage.createFromDataURL(imageOne.toDataURL()); expect(imageTwo.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); expect(imageOne.toBitmap().equals(imageTwo.toBitmap())).to.be.true(); }); it('supports a scale factor', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const expectedSize = { width: imageData.width, height: imageData.height }; const imageFromDataUrlOne = nativeImage.createFromDataURL( image.toDataURL({ scaleFactor: 1.0 })); expect(imageFromDataUrlOne.getSize()).to.deep.equal(expectedSize); const imageFromDataUrlTwo = nativeImage.createFromDataURL( image.toDataURL({ scaleFactor: 2.0 })); expect(imageFromDataUrlTwo.getSize()).to.deep.equal(expectedSize); }); }); describe('toPNG()', () => { it('returns a buffer at 1x scale factor by default', () => { const imageData = imageLogo; const imageA = nativeImage.createFromPath(imageData.path); const imageB = nativeImage.createFromBuffer(imageA.toPNG(), { width: imageA.getSize().width, height: imageA.getSize().height, scaleFactor: 2.0 }); expect(imageB.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); const imageC = nativeImage.createFromBuffer(imageB.toPNG()); expect(imageC.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); expect(imageB.toBitmap().equals(imageC.toBitmap())).to.be.true(); }); it('supports a scale factor', () => { const imageData = imageLogo; const image = nativeImage.createFromPath(imageData.path); const imageFromBufferOne = nativeImage.createFromBuffer( image.toPNG({ scaleFactor: 1.0 })); expect(imageFromBufferOne.getSize()).to.deep.equal( { width: imageData.width, height: imageData.height }); const imageFromBufferTwo = nativeImage.createFromBuffer( image.toPNG({ scaleFactor: 2.0 }), { scaleFactor: 2.0 }); expect(imageFromBufferTwo.getSize()).to.deep.equal( { width: imageData.width / 2, height: imageData.height / 2 }); }); }); describe('createFromPath(path)', () => { it('returns an empty image for invalid paths', () => { expect(nativeImage.createFromPath('').isEmpty()).to.be.true(); expect(nativeImage.createFromPath('does-not-exist.png').isEmpty()).to.be.true(); expect(nativeImage.createFromPath('does-not-exist.ico').isEmpty()).to.be.true(); expect(nativeImage.createFromPath(__dirname).isEmpty()).to.be.true(); expect(nativeImage.createFromPath(__filename).isEmpty()).to.be.true(); }); it('loads images from paths relative to the current working directory', () => { const imagePath = path.relative('.', path.join(fixturesPath, 'assets', 'logo.png')); const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); it('loads images from paths with `.` segments', () => { const imagePath = `${path.join(fixturesPath)}${path.sep}.${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); it('loads images from paths with `..` segments', () => { const imagePath = `${path.join(fixturesPath, 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 538, height: 190 }); }); ifit(process.platform === 'darwin')('Gets an NSImage pointer on macOS', function () { const imagePath = `${path.join(fixturesPath, 'api')}${path.sep}..${path.sep}${path.join('assets', 'logo.png')}`; const image = nativeImage.createFromPath(imagePath); const nsimage = image.getNativeHandle(); expect(nsimage).to.have.lengthOf(8); // If all bytes are null, that's Bad const allBytesAreNotNull = nsimage.reduce((acc, x) => acc || (x !== 0), false); expect(allBytesAreNotNull); }); ifit(process.platform === 'win32')('loads images from .ico files on Windows', function () { const imagePath = path.join(fixturesPath, 'assets', 'icon.ico'); const image = nativeImage.createFromPath(imagePath); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 256, height: 256 }); }); }); describe('createFromNamedImage(name)', () => { it('returns empty for invalid options', () => { const image = nativeImage.createFromNamedImage('totally_not_real'); expect(image.isEmpty()).to.be.true(); }); ifit(process.platform !== 'darwin')('returns empty on non-darwin platforms', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate'); expect(image.isEmpty()).to.be.true(); }); ifit(process.platform === 'darwin')('returns a valid image on darwin', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate'); expect(image.isEmpty()).to.be.false(); }); ifit(process.platform === 'darwin')('returns allows an HSL shift for a valid image on darwin', function () { const image = nativeImage.createFromNamedImage('NSActionTemplate', [0.5, 0.2, 0.8]); expect(image.isEmpty()).to.be.false(); }); }); describe('resize(options)', () => { it('returns a resized image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); for (const [resizeTo, expectedSize] of new Map([ [{}, { width: 538, height: 190 }], [{ width: 269 }, { width: 269, height: 95 }], [{ width: 600 }, { width: 600, height: 212 }], [{ height: 95 }, { width: 269, height: 95 }], [{ height: 200 }, { width: 566, height: 200 }], [{ width: 80, height: 65 }, { width: 80, height: 65 }], [{ width: 600, height: 200 }, { width: 600, height: 200 }], [{ width: 0, height: 0 }, { width: 0, height: 0 }], [{ width: -1, height: -1 }, { width: 0, height: 0 }] ])) { const actualSize = image.resize(resizeTo).getSize(); expect(actualSize).to.deep.equal(expectedSize); } }); it('returns an empty image when called on an empty image', () => { expect(nativeImage.createEmpty().resize({ width: 1, height: 1 }).isEmpty()).to.be.true(); expect(nativeImage.createEmpty().resize({ width: 0, height: 0 }).isEmpty()).to.be.true(); }); it('supports a quality option', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const good = image.resize({ width: 100, height: 100, quality: 'good' }); const better = image.resize({ width: 100, height: 100, quality: 'better' }); const best = image.resize({ width: 100, height: 100, quality: 'best' }); expect(good.toPNG()).to.have.lengthOf.at.most(better.toPNG().length); expect(better.toPNG()).to.have.lengthOf.below(best.toPNG().length); }); }); describe('crop(bounds)', () => { it('returns an empty image when called on an empty image', () => { expect(nativeImage.createEmpty().crop({ width: 1, height: 2, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(nativeImage.createEmpty().crop({ width: 0, height: 0, x: 0, y: 0 }).isEmpty()).to.be.true(); }); it('returns an empty image when the bounds are invalid', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); expect(image.crop({ width: 0, height: 0, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: -1, height: 10, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: 10, height: -35, x: 0, y: 0 }).isEmpty()).to.be.true(); expect(image.crop({ width: 100, height: 100, x: 1000, y: 1000 }).isEmpty()).to.be.true(); }); it('returns a cropped image', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const cropA = image.crop({ width: 25, height: 64, x: 0, y: 0 }); const cropB = image.crop({ width: 25, height: 64, x: 30, y: 40 }); expect(cropA.getSize()).to.deep.equal({ width: 25, height: 64 }); expect(cropB.getSize()).to.deep.equal({ width: 25, height: 64 }); expect(cropA.toPNG().equals(cropB.toPNG())).to.be.false(); }); it('toBitmap() returns a buffer of the right size', () => { const image = nativeImage.createFromPath(path.join(fixturesPath, 'assets', 'logo.png')); const crop = image.crop({ width: 25, height: 64, x: 0, y: 0 }); expect(crop.toBitmap().length).to.equal(25 * 64 * 4); }); }); describe('getAspectRatio()', () => { it('returns an aspect ratio of an empty image', () => { expect(nativeImage.createEmpty().getAspectRatio()).to.equal(1.0); }); it('returns an aspect ratio of an image', () => { const imageData = imageLogo; // imageData.width / imageData.height = 2.831578947368421 const expectedAspectRatio = 2.8315789699554443; const image = nativeImage.createFromPath(imageData.path); expect(image.getAspectRatio()).to.equal(expectedAspectRatio); }); }); ifdescribe(process.platform !== 'linux')('createThumbnailFromPath(path, size)', () => { it('throws when invalid size is passed', async () => { const badSize = { width: -1, height: -1 }; await expect( nativeImage.createThumbnailFromPath('path', badSize) ).to.eventually.be.rejectedWith('size must not be empty'); }); it('throws when a bad path is passed', async () => { const badPath = process.platform === 'win32' ? '\\hey\\hi\\hello' : '/hey/hi/hello'; const goodSize = { width: 100, height: 100 }; await expect( nativeImage.createThumbnailFromPath(badPath, goodSize) ).to.eventually.be.rejected(); }); it('returns native image given valid params', async () => { const goodPath = path.join(fixturesPath, 'assets', 'logo.png'); const goodSize = { width: 100, height: 100 }; const result = await nativeImage.createThumbnailFromPath(goodPath, goodSize); expect(result.isEmpty()).to.equal(false); }); }); describe('addRepresentation()', () => { it('does not add representation when the buffer is too small', () => { const image = nativeImage.createEmpty(); image.addRepresentation({ buffer: Buffer.from([1, 2, 3, 4]), width: 100, height: 100 }); expect(image.isEmpty()).to.be.true(); }); it('supports adding a buffer representation for a scale factor', () => { const image = nativeImage.createEmpty(); const imageDataOne = image1x1; image.addRepresentation({ scaleFactor: 1.0, buffer: nativeImage.createFromPath(imageDataOne.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1]); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, buffer: nativeImage.createFromPath(imageDataTwo.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1, 2]); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 3.0, buffer: nativeImage.createFromPath(imageDataThree.path).toPNG() }); expect(image.getScaleFactors()).to.deep.equal([1, 2, 3]); image.addRepresentation({ scaleFactor: 4.0, buffer: 'invalid' as any }); // this one failed, so it shouldn't show up in the scale factors expect(image.getScaleFactors()).to.deep.equal([1, 2, 3]); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 1, height: 1 }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); expect(image.toDataURL({ scaleFactor: 3.0 })).to.equal(imageDataThree.dataUrl); expect(image.toDataURL({ scaleFactor: 4.0 })).to.equal(imageDataThree.dataUrl); }); it('supports adding a data URL representation for a scale factor', () => { const image = nativeImage.createEmpty(); const imageDataOne = image1x1; image.addRepresentation({ scaleFactor: 1.0, dataURL: imageDataOne.dataUrl }); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataTwo.dataUrl }); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 3.0, dataURL: imageDataThree.dataUrl }); image.addRepresentation({ scaleFactor: 4.0, dataURL: 'invalid' }); expect(image.isEmpty()).to.be.false(); expect(image.getSize()).to.deep.equal({ width: 1, height: 1 }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); expect(image.toDataURL({ scaleFactor: 3.0 })).to.equal(imageDataThree.dataUrl); expect(image.toDataURL({ scaleFactor: 4.0 })).to.equal(imageDataThree.dataUrl); }); it('supports adding a representation to an existing image', () => { const imageDataOne = image1x1; const image = nativeImage.createFromPath(imageDataOne.path); const imageDataTwo = image2x2; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataTwo.dataUrl }); const imageDataThree = image3x3; image.addRepresentation({ scaleFactor: 2.0, dataURL: imageDataThree.dataUrl }); expect(image.toDataURL({ scaleFactor: 1.0 })).to.equal(imageDataOne.dataUrl); expect(image.toDataURL({ scaleFactor: 2.0 })).to.equal(imageDataTwo.dataUrl); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,340
[Bug]: getSize() is incorrect if the nativeImage is created by createThumbnailFromPath()
### 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 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 (22D68) ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior ```js const image = await nativeImage.createThumbnailFromPath(filePath, {width: 2000, height:2000}) const size = image.getSize() //<- expect the real thumbnail size, but it's always {2000, 2000} ``` getSize() is incorrect if the nativeImage is created by createThumbnailFromPath() ### Actual Behavior size = the maxSize passed in ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37340
https://github.com/electron/electron/pull/37362
f33bf2a27113bd9cd92bdd35233107779fc79f47
8ee58e18fd31a7d33ccab78820d61bab9ec1ec69
2023-02-19T03:16:15Z
c++
2023-03-09T02:48:29Z
spec/fixtures/assets/capybara.png
closed
electron/electron
https://github.com/electron/electron
37,495
[Bug]: Window showing on 'open-url' with preventDefault()
### 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.3.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should not show up. ### Actual Behavior The window shows up. ### Testcase Gist URL https://gist.github.com/vothvovo/00b6932c52d49c2ecf42853bd5db778a ### Additional Information You have to build the gist to test it because otherwise the custom uri schema won't register.
https://github.com/electron/electron/issues/37495
https://github.com/electron/electron/pull/37564
3b69a542fbb1a84a3d2b531a152f18e9e88b1666
e480cb7103df6702d0364cf76d1f20724efc49dc
2023-03-04T13:08:55Z
c++
2023-03-14T13:17:28Z
docs/api/app.md
# app > Control your application's event lifecycle. Process: [Main](../glossary.md#main-process) The following example shows how to quit the application when the last window is closed: ```javascript const { app } = require('electron') app.on('window-all-closed', () => { app.quit() }) ``` ## Events The `app` object emits the following events: ### Event: 'will-finish-launching' Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of `NSApplication`. In most cases, you should do everything in the `ready` event handler. ### Event: 'ready' Returns: * `event` Event * `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse) that was used to open the application, if it was launched from Notification Center. You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()` to get a Promise that is fulfilled when Electron is initialized. ### Event: 'window-all-closed' Emitted when all windows have been closed. If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will first try to close all the windows and then emit the `will-quit` event, and in this case the `window-all-closed` event would not be emitted. ### Event: 'before-quit' Returns: * `event` Event Emitted before the application starts closing its windows. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. **Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`, then `before-quit` is emitted *after* emitting `close` event on all windows and closing them. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'will-quit' Returns: * `event` Event Emitted when all windows have been closed and the application will quit. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. See the description of the `window-all-closed` event for the differences between the `will-quit` and `window-all-closed` events. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'quit' Returns: * `event` Event * `exitCode` Integer Emitted when the application is quitting. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'open-file' _macOS_ Returns: * `event` Event * `path` string Emitted when the user wants to open a file with the application. The `open-file` event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. `open-file` is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the `open-file` event very early in your application startup to handle this case (even before the `ready` event is emitted). You should call `event.preventDefault()` if you want to handle this event. On Windows, you have to parse `process.argv` (in the main process) to get the filepath. ### Event: 'open-url' _macOS_ Returns: * `event` Event * `url` string Emitted when the user wants to open a URL with the application. Your application's `Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. You should call `event.preventDefault()` if you want to handle this event. As with the `open-file` event, be sure to register a listener for the `open-url` event early in your application startup to detect if the the application being is being opened to handle a URL. If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application. ### Event: 'activate' _macOS_ Returns: * `event` Event * `hasVisibleWindows` boolean Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon. ### Event: 'did-become-active' _macOS_ Returns: * `event` Event Emitted when mac application become active. Difference from `activate` event is that `did-become-active` is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. ### Event: 'continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity on another device. * `details` Object * `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available. Emitted during [Handoff][handoff] when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. A user activity can be continued only in an app that has the same developer Team ID as the activity's source app and that supports the activity's type. Supported activity types are specified in the app's `Info.plist` under the `NSUserActivityTypes` key. ### Event: 'will-continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. Emitted during [Handoff][handoff] before an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'continue-activity-error' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `error` string - A string with the error's localized description. Emitted during [Handoff][handoff] when an activity from a different device fails to be resumed. ### Event: 'activity-was-continued' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted during [Handoff][handoff] after an activity from this device was successfully resumed on another one. ### Event: 'update-activity-state' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called. ### Event: 'new-window-for-tab' _macOS_ Returns: * `event` Event Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current `BrowserWindow` has a `tabbingIdentifier` ### Event: 'browser-window-blur' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets blurred. ### Event: 'browser-window-focus' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets focused. ### Event: 'browser-window-created' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a new [browserWindow](browser-window.md) is created. ### Event: 'web-contents-created' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) Emitted when a new [webContents](web-contents.md) is created. ### Event: 'certificate-error' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` string * `error` string - The error code * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Whether to consider the certificate as trusted * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`, to trust the certificate you should prevent the default behavior with `event.preventDefault()` and call `callback(true)`. ```javascript const { app } = require('electron') app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { if (url === 'https://github.com') { // Verification logic. event.preventDefault() callback(true) } else { callback(false) } }) ``` ### Event: 'select-client-certificate' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) (optional) Emitted when a client certificate is requested. The `url` corresponds to the navigation entry requesting the client certificate and `callback` can be called with an entry filtered from the list. Using `event.preventDefault()` prevents the application from using the first certificate from the store. ```javascript const { app } = require('electron') app.on('select-client-certificate', (event, webContents, url, list, callback) => { event.preventDefault() callback(list[0]) }) ``` ### Event: 'login' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `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 default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call `callback(username, password)` with the credentials. ```javascript const { app } = require('electron') app.on('login', (event, webContents, details, authInfo, callback) => { event.preventDefault() callback('username', 'secret') }) ``` If `callback` is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page. ### Event: 'gpu-info-update' Emitted whenever there is a GPU info update. ### Event: 'gpu-process-crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the GPU process crashes or is killed. **Deprecated:** This event is superceded by the `child-process-gone` event which contains more information about why the child 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: 'renderer-process-crashed' _Deprecated_ Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `killed` boolean Emitted when the renderer process of `webContents` 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 * `webContents` [WebContents](web-contents.md) * `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: 'child-process-gone' Returns: * `event` Event * `details` Object * `type` string - Process type. One of the following values: * `Utility` * `Zygote` * `Sandbox helper` * `GPU` * `Pepper Plugin` * `Pepper Plugin Broker` * `Unknown` * `reason` string - The reason the child 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` number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows). * `serviceName` string (optional) - The non-localized name of the process. * `name` string (optional) - The name of the process. Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc. Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes. ### Event: 'accessibility-support-changed' _macOS_ _Windows_ Returns: * `event` Event * `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility support is enabled, `false` otherwise. Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### Event: 'session-created' Returns: * `session` [Session](session.md) Emitted when Electron has created a new `session`. ```javascript const { app } = require('electron') app.on('session-created', (session) => { console.log(session) }) ``` ### Event: 'second-instance' Returns: * `event` Event * `argv` string[] - An array of the second instance's command line arguments * `workingDirectory` string - The second instance's working directory * `additionalData` unknown - A JSON object of additional data passed from the second instance This event will be emitted inside the primary instance of your application when a second instance has been executed and calls `app.requestSingleInstanceLock()`. `argv` is an Array of the second instance's command line arguments, and `workingDirectory` is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized. **Note:** `argv` will not be exactly the same list of arguments as those passed to the second instance. The order might change and additional arguments might be appended. If you need to maintain the exact same arguments, it's advised to use `additionalData` instead. **Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments. This event is guaranteed to be emitted after the `ready` event of `app` gets emitted. **Note:** Extra command line arguments might be added by Chromium, such as `--original-process-start-time`. ## Methods The `app` object has the following methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. ### `app.quit()` Try to close all windows. The `before-quit` event will be emitted first. If all windows are successfully closed, the `will-quit` event will be emitted and by default the application will terminate. This method guarantees that all `beforeunload` and `unload` event handlers are correctly executed. It is possible that a window cancels the quitting by returning `false` in the `beforeunload` event handler. ### `app.exit([exitCode])` * `exitCode` Integer (optional) Exits immediately with `exitCode`. `exitCode` defaults to 0. All windows will be closed immediately without asking the user, and the `before-quit` and `will-quit` events will not be emitted. ### `app.relaunch([options])` * `options` Object (optional) * `args` string[] (optional) * `execPath` string (optional) Relaunches the app when current instance exits. By default, the new instance will use the same working directory and command line arguments with current instance. When `args` is specified, the `args` will be passed as command line arguments instead. When `execPath` is specified, the `execPath` will be executed for relaunch instead of current app. Note that this method does not quit the app when executed, you have to call `app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. When `app.relaunch` is called for multiple times, multiple instances will be started after current instance exited. An example of restarting current instance immediately and adding a new command line argument to the new instance: ```javascript const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` ### `app.isReady()` Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise. See also `app.whenReady()`. ### `app.whenReady()` Returns `Promise<void>` - fulfilled when Electron is initialized. May be used as a convenient alternative to checking `app.isReady()` and subscribing to the `ready` event if the app is not ready yet. ### `app.focus([options])` * `options` Object (optional) * `steal` boolean _macOS_ - Make the receiver the active app even if another app is currently active. On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window. You should seek to use the `steal` option as sparingly as possible. ### `app.hide()` _macOS_ Hides all application windows without minimizing them. ### `app.isHidden()` _macOS_ Returns `boolean` - `true` if the application—including all of its windows—is hidden (e.g. with `Command-H`), `false` otherwise. ### `app.show()` _macOS_ Shows application windows after they were hidden. Does not automatically focus them. ### `app.setAppLogsPath([path])` * `path` string (optional) - A custom path for your logs. Must be absolute. Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`. Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_. ### `app.getAppPath()` Returns `string` - The current application directory. ### `app.getPath(name)` * `name` string - You can request the following paths by the name: * `home` User's home directory. * `appData` Per-user application data directory, which by default points to: * `%APPDATA%` on Windows * `$XDG_CONFIG_HOME` or `~/.config` on Linux * `~/Library/Application Support` on macOS * `userData` The directory for storing your app's configuration files, which by default is the `appData` directory appended with your app's name. By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage. * `sessionData` The directory for storing data generated by `Session`, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points to `userData`. Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting the `userData` directory. * `temp` Temporary directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. * `desktop` The current user's Desktop directory. * `documents` Directory for a user's "My Documents". * `downloads` Directory for a user's downloads. * `music` Directory for a user's music. * `pictures` Directory for a user's pictures. * `videos` Directory for a user's videos. * `recent` Directory for the user's recent files (Windows only). * `logs` Directory for your app's log folder. * `crashDumps` Directory where crash dumps are stored. Returns `string` - A path to a special directory or file associated with `name`. On failure, an `Error` is thrown. If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter. ### `app.getFileIcon(path[, options])` * `path` string * `options` Object (optional) * `size` string * `small` - 16x16 * `normal` - 32x32 * `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_. Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md). Fetches a path's associated icon. On _Windows_, there a 2 kinds of icons: * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. On _Linux_ and _macOS_, icons depend on the application associated with file mime type. ### `app.setPath(name, path)` * `name` string * `path` string Overrides the `path` to a special directory or file associated with `name`. If the path specifies a directory that does not exist, an `Error` is thrown. In that case, the directory should be created with `fs.mkdirSync` or similar. You can only override paths of a `name` defined in `app.getPath`. By default, web pages' cookies and caches will be stored under the `sessionData` directory. If you want to change this location, you have to override the `sessionData` path before the `ready` event of the `app` module is emitted. ### `app.getVersion()` Returns `string` - The version of the loaded application. If no version is found in the application's `package.json` file, the version of the current bundle or executable is returned. ### `app.getName()` Returns `string` - The current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.setName(name)` * `name` string Overrides the current application's name. **Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses. ### `app.getLocale()` Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library. Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc). To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md). **Note:** When distributing your packaged app, you have to also ship the `locales` folder. **Note:** This API must be called after the `ready` event is emitted. **Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `app.getLocaleCountryCode()` Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs. **Note:** When unable to detect locale country code, it returns empty string. ### `app.getSystemLocale()` Returns `string` - The current system locale. On Windows and Linux, it is fetched using Chromium's `i18n` library. On macOS, `[NSLocale currentLocale]` is used instead. To get the user's current system language, which is not always the same as the locale, it is better to use [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). Different operating systems also use the regional data differently: * Windows 11 uses the regional format for numbers, dates, and times. * macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use. Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS. **Note:** This API must be called after the `ready` event is emitted. **Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `app.getPreferredSystemLanguages()` Returns `string[]` - The user's preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings. The API uses `GlobalizationPreferences` (with a fallback to `GetSystemPreferredUILanguages`) on Windows, `\[NSLocale preferredLanguages\]` on macOS, and `g_get_language_names` on Linux. This API can be used for purposes such as deciding what language to present the application in. Here are some examples of return values of the various language and locale APIs with different configurations: * For Windows, where the application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America): * `app.getLocale()` returns `'de'` * `app.getSystemLocale()` returns `'fi-FI'` * `app.getPreferredSystemLanguages()` returns `['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']` * On macOS, where the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America): * `app.getLocale()` returns `'de'` * `app.getSystemLocale()` returns `'fr-FI'` * `app.getPreferredSystemLanguages()` returns `['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']` Both the available languages and regions and the possible return values differ between the two operating systems. As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn't need to have Finnish as a preferred language to use Finland as the region,and the country code `FI` is used as the country code for preferred system languages that do not have associated countries in the language name. ### `app.addRecentDocument(path)` _macOS_ _Windows_ * `path` string Adds `path` to the recent documents list. This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu. ### `app.clearRecentDocuments()` _macOS_ _Windows_ Clears the recent documents list. ### `app.setAsDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. For example, if you want your app to handle `electron://` links, call this method with `electron` as the parameter. * `path` string (optional) _Windows_ - The path to the Electron executable. Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Arguments passed to the executable. Defaults to an empty array Returns `boolean` - Whether the call succeeded. Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with `your-protocol://` will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter. **Note:** On macOS, you can only register protocols that have been added to your app's `info.plist`, which cannot be modified at runtime. However, you can change the file during build time via [Electron Forge][electron-forge], [Electron Packager][electron-packager], or by editing `info.plist` with a text editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details. **Note:** In a Windows Store environment (when packaged as an `appx`) this API will return `true` for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must [declare the protocol in your manifest](https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol). The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally. ### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_ * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the call succeeded. This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. ### `app.isDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the current executable is the default handler for a protocol (aka URI scheme). **Note:** On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the macOS machine. Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally. ### `app.getApplicationNameForProtocol(url)` * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `string` - Name of the application handling the protocol, or an empty string if there is no handler. For instance, if Electron is the default handler of the URL, this could be `Electron` on Windows and Mac. However, don't rely on the precise format which is not guaranteed to remain unchanged. Expect a different format on Linux, possibly with a `.desktop` suffix. This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL. ### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_ * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `Promise<Object>` - Resolve with an object containing the following: * `icon` NativeImage - the display icon of the app handling the protocol. * `path` string - installation path of the app handling the protocol. * `name` string - display name of the app handling the protocol. This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL. ### `app.setUserTasks(tasks)` _Windows_ * `tasks` [Task[]](structures/task.md) - Array of `Task` objects Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows. `tasks` is an array of [`Task`](structures/task.md) objects. Returns `boolean` - Whether the call succeeded. **Note:** If you'd like to customize the Jump List even more use `app.setJumpList(categories)` instead. ### `app.getJumpListSettings()` _Windows_ Returns `Object`: * `minItems` Integer - The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the [MSDN docs][JumpListBeginListMSDN]). * `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem` objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the **next** call to `app.setJumpList()`, Windows will not display any custom category that contains any of the removed items. ### `app.setJumpList(categories)` _Windows_ * `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects. Returns `string` Sets or removes a custom Jump List for the application, and returns one of the following strings: * `ok` - Nothing went wrong. * `error` - One or more errors occurred, enable runtime logging to figure out the likely cause. * `invalidSeparatorError` - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard `Tasks` category. * `fileTypeRegistrationError` - An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle. * `customCategoryAccessDeniedError` - Custom categories can't be added to the Jump List due to user privacy or group policy settings. If `categories` is `null` the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows). **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` property set then its `type` is assumed to be `tasks`. If the `name` property is set but the `type` property is omitted then the `type` is assumed to be `custom`. **Note:** Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until **after** the next successful call to `app.setJumpList(categories)`. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using `app.getJumpListSettings()`. **Note:** The maximum length of a Jump List item's `description` property is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed. Here's a very simple example of creating a custom Jump List: ```javascript const { app } = require('electron') app.setJumpList([ { type: 'custom', name: 'Recent Projects', items: [ { type: 'file', path: 'C:\\Projects\\project1.proj' }, { type: 'file', path: 'C:\\Projects\\project2.proj' } ] }, { // has a name so `type` is assumed to be "custom" name: 'Tools', items: [ { type: 'task', title: 'Tool A', program: process.execPath, args: '--run-tool-a', icon: process.execPath, iconIndex: 0, description: 'Runs Tool A' }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', icon: process.execPath, iconIndex: 0, description: 'Runs Tool B' } ] }, { type: 'frequent' }, { // has no name and no type so `type` is assumed to be "tasks" items: [ { type: 'task', title: 'New Project', program: process.execPath, args: '--new-project', description: 'Create a new project.' }, { type: 'separator' }, { type: 'task', title: 'Recover Project', program: process.execPath, args: '--recover-project', description: 'Recover Project' } ] } ]) ``` ### `app.requestSingleInstanceLock([additionalData])` * `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately. I.e. This method returns `true` if your process is the primary instance of your application and your app should continue loading. It returns `false` if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock. On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the `open-file` and `open-url` events will be emitted for that. However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance. An example of activating the window of primary instance when a second instance starts: ```javascript const { app } = require('electron') let myWindow = null const additionalData = { myKey: 'myValue' } const gotTheLock = app.requestSingleInstanceLock(additionalData) if (!gotTheLock) { app.quit() } else { app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => { // Print out data received from the second instance. console.log(additionalData) // Someone tried to run a second instance, we should focus our window. if (myWindow) { if (myWindow.isMinimized()) myWindow.restore() myWindow.focus() } }) // Create myWindow, load the rest of the app, etc... app.whenReady().then(() => { myWindow = createWindow() }) } ``` ### `app.hasSingleInstanceLock()` Returns `boolean` This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with `app.requestSingleInstanceLock()` and release with `app.releaseSingleInstanceLock()` ### `app.releaseSingleInstanceLock()` Releases all locks that were created by `requestSingleInstanceLock`. This will allow multiple instances of the application to once again run side by side. ### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. * `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be `http` or `https`. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [Handoff][handoff] to another device afterward. ### `app.getCurrentActivityType()` _macOS_ Returns `string` - The type of the currently running activity. ### `app.invalidateCurrentActivity()` _macOS_ Invalidates the current [Handoff][handoff] user activity. ### `app.resignCurrentActivity()` _macOS_ Marks the current [Handoff][handoff] user activity as inactive without invalidating it. ### `app.updateCurrentActivity(type, userInfo)` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. Updates the current activity if its type matches `type`, merging the entries from `userInfo` into its current `userInfo` dictionary. ### `app.setAppUserModelId(id)` _Windows_ * `id` string Changes the [Application User Model ID][app-user-model-id] to `id`. ### `app.setActivationPolicy(policy)` _macOS_ * `policy` string - Can be 'regular', 'accessory', or 'prohibited'. Sets the activation policy for a given app. Activation policy types: * 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface. * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows. * 'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated. ### `app.importCertificate(options, callback)` _Linux_ * `options` Object * `certificate` string - Path for the pkcs12 file. * `password` string - Passphrase for the certificate. * `callback` Function * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. `callback` is called with the `result` of import operation, a value of `0` indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). ### `app.configureHostResolver(options)` * `options` Object * `enableBuiltInResolver` boolean (optional) - Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. * `secureDnsMode` string (optional) - Can be "off", "automatic" or "secure". Configures the DNS-over-HTTP mode. When "off", no DoH lookups will be performed. When "automatic", DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When "secure", only DoH lookups will be performed. Defaults to "automatic". * `secureDnsServers` string[]&#32;(optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for [some DNS providers][doh-providers], the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list. * `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true. Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order: 1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then 2. the built-in resolver (enabled on macOS only by default), then 3. the system's resolver (e.g. `getaddrinfo`). This can be configured to either restrict usage of non-encrypted DNS (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). It is also possible to enable or disable the built-in resolver. To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user's DNS configuration does not include a provider that supports DoH. ```js app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) ``` This API must be called after the `ready` event is emitted. [doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc [RFC8484 § 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3 ### `app.disableHardwareAcceleration()` Disables hardware acceleration for current app. This method can only be called before app is ready. ### `app.disableDomainBlockingFor3DAPIs()` By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior. This method can only be called before app is ready. ### `app.getAppMetrics()` Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app. ### `app.getGPUFeatureStatus()` Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`. **Note:** This information is only usable after the `gpu-info-update` event is emitted. ### `app.getGPUInfo(infoType)` * `infoType` string - Can be `basic` or `complete`. Returns `Promise<unknown>` For `infoType` equal to `complete`: Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page. For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response: ```js { auxAttributes: { amdSwitchable: true, canSupportThreadedTextureMailbox: false, directComposition: false, directRendering: true, glResetNotificationStrategy: 0, inProcessGpu: true, initializationTime: 0, jpegDecodeAcceleratorSupported: false, optimus: false, passthroughCmdDecoder: false, sandboxed: false, softwareRendering: false, supportsOverlays: false, videoDecodeAcceleratorFlags: 0 }, gpuDevice: [{ active: true, deviceId: 26657, vendorId: 4098 }, { active: false, deviceId: 3366, vendorId: 32902 }], machineModelName: 'MacBookPro', machineModelVersion: '11.5' } ``` Using `basic` should be preferred if only basic information like `vendorId` or `deviceId` is needed. ### `app.setBadgeCount([count])` _Linux_ _macOS_ * `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display. Returns `boolean` - Whether the call succeeded. Sets the counter badge for current app. Setting the count to `0` will hide the badge. On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. ### `app.getBadgeCount()` _Linux_ _macOS_ Returns `Integer` - The current value displayed in the counter badge. ### `app.isUnityRunning()` _Linux_ Returns `boolean` - Whether the current desktop environment is Unity launcher. ### `app.getLoginItemSettings([options])` _macOS_ _Windows_ * `options` Object (optional) * `path` string (optional) _Windows_ - The executable path to compare against. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to compare against. Defaults to an empty array. If you provided `path` and `args` options to `app.setLoginItemSettings`, then you need to pass the same arguments here for `openAtLogin` to be set correctly. Returns `Object`: * `openAtLogin` boolean - `true` if the app is set to open at login. * `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login automatically. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on [MAS builds][mas-builds]. * `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on [MAS builds][mas-builds]. * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments. * `launchItems` Object[] _Windows_ * `name` string _Windows_ - name value of a registry entry. * `path` string _Windows_ - The executable to an app that corresponds to a registry entry. * `args` string[] _Windows_ - the command-line arguments to pass to the executable. * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings. ### `app.setLoginItemSettings(settings)` _macOS_ _Windows_ * `settings` Object * `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove the app as a login item. Defaults to `false`. * `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to `false`. The user can edit this setting from the System Preferences so `app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app is opened to know the current value. This setting is not available on [MAS builds][mas-builds]. * `path` string (optional) _Windows_ - The executable to launch at login. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes. * `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings. Defaults to `true`. * `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId(). Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], you'll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example: ``` javascript const appFolder = path.dirname(process.execPath) const updateExe = path.resolve(appFolder, '..', 'Update.exe') const exeName = path.basename(process.execPath) app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: [ '--processStart', `"${exeName}"`, '--process-start-args', `"--hidden"` ] }) ``` ### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_ Returns `boolean` - `true` if Chrome's accessibility support is enabled, `false` otherwise. This API will return `true` if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_ * `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.showAboutPanel()` Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously. ### `app.setAboutPanelOptions(options)` * `options` Object * `applicationName` string (optional) - The app's name. * `applicationVersion` string (optional) - The app's version. * `copyright` string (optional) - Copyright information. * `version` string (optional) _macOS_ - The app's build version number. * `credits` string (optional) _macOS_ _Windows_ - Credit information. * `authors` string[] (optional) _Linux_ - List of app authors. * `website` string (optional) _Linux_ - The app's website. * `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults. If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information. ### `app.isEmojiPanelSupported()` Returns `boolean` - whether or not the current OS version allows for native emoji pickers. ### `app.showEmojiPanel()` _macOS_ _Windows_ Show the platform's native emoji picker. ### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_ * `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods. Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted. ```js // Start accessing the file. const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data) // You can now access the file outside of the sandbox 🎉 // Remember to stop accessing the file once you've finished with it. stopAccessingSecurityScopedResource() ``` Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works. ### `app.enableSandbox()` Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in WebPreferences. This method can only be called before app is ready. ### `app.isInApplicationsFolder()` _macOS_ Returns `boolean` - Whether the application is currently running from the systems Application folder. Use in combination with `app.moveToApplicationsFolder()` ### `app.moveToApplicationsFolder([options])` _macOS_ * `options` Object (optional) * `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure. * `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running. Returns `boolean` - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch. No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the [`dialog`](dialog.md) API. **NOTE:** This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong. By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing. For example: ```js app.moveToApplicationsFolder({ conflictHandler: (conflictType) => { if (conflictType === 'exists') { return dialog.showMessageBoxSync({ type: 'question', buttons: ['Halt Move', 'Continue Move'], defaultId: 0, message: 'An app of this name already exists' }) === 1 } } }) ``` Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place. ### `app.isSecureKeyboardEntryEnabled()` _macOS_ Returns `boolean` - whether `Secure Keyboard Entry` is enabled. By default this API will return `false`. ### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_ * `enabled` boolean - Enable or disable `Secure Keyboard Entry` Set the `Secure Keyboard Entry` is enabled in your application. By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes. See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more details. **Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed. ## Properties ### `app.accessibilitySupportEnabled` _macOS_ _Windows_ A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.applicationMenu` A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise. Users can pass a [Menu](menu.md) to set this property. ### `app.badgeCount` _Linux_ _macOS_ An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge. On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. **Note:** On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect. ### `app.commandLine` _Readonly_ A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the command line arguments that Chromium uses. ### `app.dock` _macOS_ _Readonly_ A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's dock on macOS. ### `app.isPackaged` _Readonly_ A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments. [tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-forge]: https://www.electronforge.io/ [electron-packager]: https://github.com/electron/electron-packager [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 [LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme [handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html [activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType [unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [mas-builds]: ../tutorial/mac-app-store-submission-guide.md [Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows [JumpListBeginListMSDN]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378398(v=vs.85).aspx [about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc ### `app.name` A `string` property that indicates the current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.userAgentFallback` A `string` which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the `webContents` or `session` level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used. ### `app.runningUnderRosettaTranslation` _macOS_ _Readonly_ _Deprecated_ A `boolean` which when `true` indicates that the app is currently running under the [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly. **Deprecated:** This property is superceded by the `runningUnderARM64Translation` property which detects when the app is being translated to ARM64 in both macOS and Windows. ### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_ A `boolean` which when `true` indicates that the app is currently running under an ARM64 translator (like the macOS [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)) or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)). You can use this property to prompt users to download the arm64 version of your application when they are mistakenly running the x64 version under Rosetta or WOW.
closed
electron/electron
https://github.com/electron/electron
37,495
[Bug]: Window showing on 'open-url' with preventDefault()
### 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.3.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior The window should not show up. ### Actual Behavior The window shows up. ### Testcase Gist URL https://gist.github.com/vothvovo/00b6932c52d49c2ecf42853bd5db778a ### Additional Information You have to build the gist to test it because otherwise the custom uri schema won't register.
https://github.com/electron/electron/issues/37495
https://github.com/electron/electron/pull/37564
3b69a542fbb1a84a3d2b531a152f18e9e88b1666
e480cb7103df6702d0364cf76d1f20724efc49dc
2023-03-04T13:08:55Z
c++
2023-03-14T13:17:28Z
docs/api/app.md
# app > Control your application's event lifecycle. Process: [Main](../glossary.md#main-process) The following example shows how to quit the application when the last window is closed: ```javascript const { app } = require('electron') app.on('window-all-closed', () => { app.quit() }) ``` ## Events The `app` object emits the following events: ### Event: 'will-finish-launching' Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of `NSApplication`. In most cases, you should do everything in the `ready` event handler. ### Event: 'ready' Returns: * `event` Event * `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse) that was used to open the application, if it was launched from Notification Center. You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()` to get a Promise that is fulfilled when Electron is initialized. ### Event: 'window-all-closed' Emitted when all windows have been closed. If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will first try to close all the windows and then emit the `will-quit` event, and in this case the `window-all-closed` event would not be emitted. ### Event: 'before-quit' Returns: * `event` Event Emitted before the application starts closing its windows. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. **Note:** If application quit was initiated by `autoUpdater.quitAndInstall()`, then `before-quit` is emitted *after* emitting `close` event on all windows and closing them. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'will-quit' Returns: * `event` Event Emitted when all windows have been closed and the application will quit. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. See the description of the `window-all-closed` event for the differences between the `will-quit` and `window-all-closed` events. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'quit' Returns: * `event` Event * `exitCode` Integer Emitted when the application is quitting. **Note:** On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout. ### Event: 'open-file' _macOS_ Returns: * `event` Event * `path` string Emitted when the user wants to open a file with the application. The `open-file` event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. `open-file` is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the `open-file` event very early in your application startup to handle this case (even before the `ready` event is emitted). You should call `event.preventDefault()` if you want to handle this event. On Windows, you have to parse `process.argv` (in the main process) to get the filepath. ### Event: 'open-url' _macOS_ Returns: * `event` Event * `url` string Emitted when the user wants to open a URL with the application. Your application's `Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. You should call `event.preventDefault()` if you want to handle this event. As with the `open-file` event, be sure to register a listener for the `open-url` event early in your application startup to detect if the the application being is being opened to handle a URL. If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application. ### Event: 'activate' _macOS_ Returns: * `event` Event * `hasVisibleWindows` boolean Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon. ### Event: 'did-become-active' _macOS_ Returns: * `event` Event Emitted when mac application become active. Difference from `activate` event is that `did-become-active` is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. ### Event: 'continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity on another device. * `details` Object * `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available. Emitted during [Handoff][handoff] when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. A user activity can be continued only in an app that has the same developer Team ID as the activity's source app and that supports the activity's type. Supported activity types are specified in the app's `Info.plist` under the `NSUserActivityTypes` key. ### Event: 'will-continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. Emitted during [Handoff][handoff] before an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'continue-activity-error' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `error` string - A string with the error's localized description. Emitted during [Handoff][handoff] when an activity from a different device fails to be resumed. ### Event: 'activity-was-continued' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted during [Handoff][handoff] after an activity from this device was successfully resumed on another one. ### Event: 'update-activity-state' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called. ### Event: 'new-window-for-tab' _macOS_ Returns: * `event` Event Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current `BrowserWindow` has a `tabbingIdentifier` ### Event: 'browser-window-blur' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets blurred. ### Event: 'browser-window-focus' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets focused. ### Event: 'browser-window-created' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a new [browserWindow](browser-window.md) is created. ### Event: 'web-contents-created' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) Emitted when a new [webContents](web-contents.md) is created. ### Event: 'certificate-error' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` string * `error` string - The error code * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Whether to consider the certificate as trusted * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`, to trust the certificate you should prevent the default behavior with `event.preventDefault()` and call `callback(true)`. ```javascript const { app } = require('electron') app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { if (url === 'https://github.com') { // Verification logic. event.preventDefault() callback(true) } else { callback(false) } }) ``` ### Event: 'select-client-certificate' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) (optional) Emitted when a client certificate is requested. The `url` corresponds to the navigation entry requesting the client certificate and `callback` can be called with an entry filtered from the list. Using `event.preventDefault()` prevents the application from using the first certificate from the store. ```javascript const { app } = require('electron') app.on('select-client-certificate', (event, webContents, url, list, callback) => { event.preventDefault() callback(list[0]) }) ``` ### Event: 'login' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `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 default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call `callback(username, password)` with the credentials. ```javascript const { app } = require('electron') app.on('login', (event, webContents, details, authInfo, callback) => { event.preventDefault() callback('username', 'secret') }) ``` If `callback` is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page. ### Event: 'gpu-info-update' Emitted whenever there is a GPU info update. ### Event: 'gpu-process-crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the GPU process crashes or is killed. **Deprecated:** This event is superceded by the `child-process-gone` event which contains more information about why the child 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: 'renderer-process-crashed' _Deprecated_ Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `killed` boolean Emitted when the renderer process of `webContents` 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 * `webContents` [WebContents](web-contents.md) * `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: 'child-process-gone' Returns: * `event` Event * `details` Object * `type` string - Process type. One of the following values: * `Utility` * `Zygote` * `Sandbox helper` * `GPU` * `Pepper Plugin` * `Pepper Plugin Broker` * `Unknown` * `reason` string - The reason the child 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` number - The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows). * `serviceName` string (optional) - The non-localized name of the process. * `name` string (optional) - The name of the process. Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc. Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes. ### Event: 'accessibility-support-changed' _macOS_ _Windows_ Returns: * `event` Event * `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility support is enabled, `false` otherwise. Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### Event: 'session-created' Returns: * `session` [Session](session.md) Emitted when Electron has created a new `session`. ```javascript const { app } = require('electron') app.on('session-created', (session) => { console.log(session) }) ``` ### Event: 'second-instance' Returns: * `event` Event * `argv` string[] - An array of the second instance's command line arguments * `workingDirectory` string - The second instance's working directory * `additionalData` unknown - A JSON object of additional data passed from the second instance This event will be emitted inside the primary instance of your application when a second instance has been executed and calls `app.requestSingleInstanceLock()`. `argv` is an Array of the second instance's command line arguments, and `workingDirectory` is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized. **Note:** `argv` will not be exactly the same list of arguments as those passed to the second instance. The order might change and additional arguments might be appended. If you need to maintain the exact same arguments, it's advised to use `additionalData` instead. **Note:** If the second instance is started by a different user than the first, the `argv` array will not include the arguments. This event is guaranteed to be emitted after the `ready` event of `app` gets emitted. **Note:** Extra command line arguments might be added by Chromium, such as `--original-process-start-time`. ## Methods The `app` object has the following methods: **Note:** Some methods are only available on specific operating systems and are labeled as such. ### `app.quit()` Try to close all windows. The `before-quit` event will be emitted first. If all windows are successfully closed, the `will-quit` event will be emitted and by default the application will terminate. This method guarantees that all `beforeunload` and `unload` event handlers are correctly executed. It is possible that a window cancels the quitting by returning `false` in the `beforeunload` event handler. ### `app.exit([exitCode])` * `exitCode` Integer (optional) Exits immediately with `exitCode`. `exitCode` defaults to 0. All windows will be closed immediately without asking the user, and the `before-quit` and `will-quit` events will not be emitted. ### `app.relaunch([options])` * `options` Object (optional) * `args` string[] (optional) * `execPath` string (optional) Relaunches the app when current instance exits. By default, the new instance will use the same working directory and command line arguments with current instance. When `args` is specified, the `args` will be passed as command line arguments instead. When `execPath` is specified, the `execPath` will be executed for relaunch instead of current app. Note that this method does not quit the app when executed, you have to call `app.quit` or `app.exit` after calling `app.relaunch` to make the app restart. When `app.relaunch` is called for multiple times, multiple instances will be started after current instance exited. An example of restarting current instance immediately and adding a new command line argument to the new instance: ```javascript const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` ### `app.isReady()` Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise. See also `app.whenReady()`. ### `app.whenReady()` Returns `Promise<void>` - fulfilled when Electron is initialized. May be used as a convenient alternative to checking `app.isReady()` and subscribing to the `ready` event if the app is not ready yet. ### `app.focus([options])` * `options` Object (optional) * `steal` boolean _macOS_ - Make the receiver the active app even if another app is currently active. On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application's first window. You should seek to use the `steal` option as sparingly as possible. ### `app.hide()` _macOS_ Hides all application windows without minimizing them. ### `app.isHidden()` _macOS_ Returns `boolean` - `true` if the application—including all of its windows—is hidden (e.g. with `Command-H`), `false` otherwise. ### `app.show()` _macOS_ Shows application windows after they were hidden. Does not automatically focus them. ### `app.setAppLogsPath([path])` * `path` string (optional) - A custom path for your logs. Must be absolute. Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`. Calling `app.setAppLogsPath()` without a `path` parameter will result in this directory being set to `~/Library/Logs/YourAppName` on _macOS_, and inside the `userData` directory on _Linux_ and _Windows_. ### `app.getAppPath()` Returns `string` - The current application directory. ### `app.getPath(name)` * `name` string - You can request the following paths by the name: * `home` User's home directory. * `appData` Per-user application data directory, which by default points to: * `%APPDATA%` on Windows * `$XDG_CONFIG_HOME` or `~/.config` on Linux * `~/Library/Application Support` on macOS * `userData` The directory for storing your app's configuration files, which by default is the `appData` directory appended with your app's name. By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage. * `sessionData` The directory for storing data generated by `Session`, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points to `userData`. Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting the `userData` directory. * `temp` Temporary directory. * `exe` The current executable file. * `module` The `libchromiumcontent` library. * `desktop` The current user's Desktop directory. * `documents` Directory for a user's "My Documents". * `downloads` Directory for a user's downloads. * `music` Directory for a user's music. * `pictures` Directory for a user's pictures. * `videos` Directory for a user's videos. * `recent` Directory for the user's recent files (Windows only). * `logs` Directory for your app's log folder. * `crashDumps` Directory where crash dumps are stored. Returns `string` - A path to a special directory or file associated with `name`. On failure, an `Error` is thrown. If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter. ### `app.getFileIcon(path[, options])` * `path` string * `options` Object (optional) * `size` string * `small` - 16x16 * `normal` - 32x32 * `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_. Returns `Promise<NativeImage>` - fulfilled with the app's icon, which is a [NativeImage](native-image.md). Fetches a path's associated icon. On _Windows_, there a 2 kinds of icons: * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. On _Linux_ and _macOS_, icons depend on the application associated with file mime type. ### `app.setPath(name, path)` * `name` string * `path` string Overrides the `path` to a special directory or file associated with `name`. If the path specifies a directory that does not exist, an `Error` is thrown. In that case, the directory should be created with `fs.mkdirSync` or similar. You can only override paths of a `name` defined in `app.getPath`. By default, web pages' cookies and caches will be stored under the `sessionData` directory. If you want to change this location, you have to override the `sessionData` path before the `ready` event of the `app` module is emitted. ### `app.getVersion()` Returns `string` - The version of the loaded application. If no version is found in the application's `package.json` file, the version of the current bundle or executable is returned. ### `app.getName()` Returns `string` - The current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.setName(name)` * `name` string Overrides the current application's name. **Note:** This function overrides the name used internally by Electron; it does not affect the name that the OS uses. ### `app.getLocale()` Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library. Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc). To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md). **Note:** When distributing your packaged app, you have to also ship the `locales` folder. **Note:** This API must be called after the `ready` event is emitted. **Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `app.getLocaleCountryCode()` Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs. **Note:** When unable to detect locale country code, it returns empty string. ### `app.getSystemLocale()` Returns `string` - The current system locale. On Windows and Linux, it is fetched using Chromium's `i18n` library. On macOS, `[NSLocale currentLocale]` is used instead. To get the user's current system language, which is not always the same as the locale, it is better to use [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). Different operating systems also use the regional data differently: * Windows 11 uses the regional format for numbers, dates, and times. * macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use. Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS. **Note:** This API must be called after the `ready` event is emitted. **Note:** To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `app.getPreferredSystemLanguages()` Returns `string[]` - The user's preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings. The API uses `GlobalizationPreferences` (with a fallback to `GetSystemPreferredUILanguages`) on Windows, `\[NSLocale preferredLanguages\]` on macOS, and `g_get_language_names` on Linux. This API can be used for purposes such as deciding what language to present the application in. Here are some examples of return values of the various language and locale APIs with different configurations: * For Windows, where the application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America): * `app.getLocale()` returns `'de'` * `app.getSystemLocale()` returns `'fi-FI'` * `app.getPreferredSystemLanguages()` returns `['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']` * On macOS, where the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America): * `app.getLocale()` returns `'de'` * `app.getSystemLocale()` returns `'fr-FI'` * `app.getPreferredSystemLanguages()` returns `['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']` Both the available languages and regions and the possible return values differ between the two operating systems. As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn't need to have Finnish as a preferred language to use Finland as the region,and the country code `FI` is used as the country code for preferred system languages that do not have associated countries in the language name. ### `app.addRecentDocument(path)` _macOS_ _Windows_ * `path` string Adds `path` to the recent documents list. This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu. ### `app.clearRecentDocuments()` _macOS_ _Windows_ Clears the recent documents list. ### `app.setAsDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. For example, if you want your app to handle `electron://` links, call this method with `electron` as the parameter. * `path` string (optional) _Windows_ - The path to the Electron executable. Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Arguments passed to the executable. Defaults to an empty array Returns `boolean` - Whether the call succeeded. Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with `your-protocol://` will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter. **Note:** On macOS, you can only register protocols that have been added to your app's `info.plist`, which cannot be modified at runtime. However, you can change the file during build time via [Electron Forge][electron-forge], [Electron Packager][electron-packager], or by editing `info.plist` with a text editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details. **Note:** In a Windows Store environment (when packaged as an `appx`) this API will return `true` for all calls but the registry key it sets won't be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must [declare the protocol in your manifest](https://docs.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol). The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally. ### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_ * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the call succeeded. This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. ### `app.isDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the current executable is the default handler for a protocol (aka URI scheme). **Note:** On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking `~/Library/Preferences/com.apple.LaunchServices.plist` on the macOS machine. Please refer to [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally. ### `app.getApplicationNameForProtocol(url)` * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `string` - Name of the application handling the protocol, or an empty string if there is no handler. For instance, if Electron is the default handler of the URL, this could be `Electron` on Windows and Mac. However, don't rely on the precise format which is not guaranteed to remain unchanged. Expect a different format on Linux, possibly with a `.desktop` suffix. This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL. ### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_ * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `Promise<Object>` - Resolve with an object containing the following: * `icon` NativeImage - the display icon of the app handling the protocol. * `path` string - installation path of the app handling the protocol. * `name` string - display name of the app handling the protocol. This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL. ### `app.setUserTasks(tasks)` _Windows_ * `tasks` [Task[]](structures/task.md) - Array of `Task` objects Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows. `tasks` is an array of [`Task`](structures/task.md) objects. Returns `boolean` - Whether the call succeeded. **Note:** If you'd like to customize the Jump List even more use `app.setJumpList(categories)` instead. ### `app.getJumpListSettings()` _Windows_ Returns `Object`: * `minItems` Integer - The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the [MSDN docs][JumpListBeginListMSDN]). * `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem` objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the **next** call to `app.setJumpList()`, Windows will not display any custom category that contains any of the removed items. ### `app.setJumpList(categories)` _Windows_ * `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects. Returns `string` Sets or removes a custom Jump List for the application, and returns one of the following strings: * `ok` - Nothing went wrong. * `error` - One or more errors occurred, enable runtime logging to figure out the likely cause. * `invalidSeparatorError` - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard `Tasks` category. * `fileTypeRegistrationError` - An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle. * `customCategoryAccessDeniedError` - Custom categories can't be added to the Jump List due to user privacy or group policy settings. If `categories` is `null` the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows). **Note:** If a `JumpListCategory` object has neither the `type` nor the `name` property set then its `type` is assumed to be `tasks`. If the `name` property is set but the `type` property is omitted then the `type` is assumed to be `custom`. **Note:** Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until **after** the next successful call to `app.setJumpList(categories)`. Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using `app.getJumpListSettings()`. **Note:** The maximum length of a Jump List item's `description` property is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed. Here's a very simple example of creating a custom Jump List: ```javascript const { app } = require('electron') app.setJumpList([ { type: 'custom', name: 'Recent Projects', items: [ { type: 'file', path: 'C:\\Projects\\project1.proj' }, { type: 'file', path: 'C:\\Projects\\project2.proj' } ] }, { // has a name so `type` is assumed to be "custom" name: 'Tools', items: [ { type: 'task', title: 'Tool A', program: process.execPath, args: '--run-tool-a', icon: process.execPath, iconIndex: 0, description: 'Runs Tool A' }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', icon: process.execPath, iconIndex: 0, description: 'Runs Tool B' } ] }, { type: 'frequent' }, { // has no name and no type so `type` is assumed to be "tasks" items: [ { type: 'task', title: 'New Project', program: process.execPath, args: '--new-project', description: 'Create a new project.' }, { type: 'separator' }, { type: 'task', title: 'Recover Project', program: process.execPath, args: '--recover-project', description: 'Recover Project' } ] } ]) ``` ### `app.requestSingleInstanceLock([additionalData])` * `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately. I.e. This method returns `true` if your process is the primary instance of your application and your app should continue loading. It returns `false` if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock. On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the `open-file` and `open-url` events will be emitted for that. However when users start your app in command line, the system's single instance mechanism will be bypassed, and you have to use this method to ensure single instance. An example of activating the window of primary instance when a second instance starts: ```javascript const { app } = require('electron') let myWindow = null const additionalData = { myKey: 'myValue' } const gotTheLock = app.requestSingleInstanceLock(additionalData) if (!gotTheLock) { app.quit() } else { app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => { // Print out data received from the second instance. console.log(additionalData) // Someone tried to run a second instance, we should focus our window. if (myWindow) { if (myWindow.isMinimized()) myWindow.restore() myWindow.focus() } }) // Create myWindow, load the rest of the app, etc... app.whenReady().then(() => { myWindow = createWindow() }) } ``` ### `app.hasSingleInstanceLock()` Returns `boolean` This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with `app.requestSingleInstanceLock()` and release with `app.releaseSingleInstanceLock()` ### `app.releaseSingleInstanceLock()` Releases all locks that were created by `requestSingleInstanceLock`. This will allow multiple instances of the application to once again run side by side. ### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. * `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be `http` or `https`. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [Handoff][handoff] to another device afterward. ### `app.getCurrentActivityType()` _macOS_ Returns `string` - The type of the currently running activity. ### `app.invalidateCurrentActivity()` _macOS_ Invalidates the current [Handoff][handoff] user activity. ### `app.resignCurrentActivity()` _macOS_ Marks the current [Handoff][handoff] user activity as inactive without invalidating it. ### `app.updateCurrentActivity(type, userInfo)` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. Updates the current activity if its type matches `type`, merging the entries from `userInfo` into its current `userInfo` dictionary. ### `app.setAppUserModelId(id)` _Windows_ * `id` string Changes the [Application User Model ID][app-user-model-id] to `id`. ### `app.setActivationPolicy(policy)` _macOS_ * `policy` string - Can be 'regular', 'accessory', or 'prohibited'. Sets the activation policy for a given app. Activation policy types: * 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface. * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows. * 'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated. ### `app.importCertificate(options, callback)` _Linux_ * `options` Object * `certificate` string - Path for the pkcs12 file. * `password` string - Passphrase for the certificate. * `callback` Function * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. `callback` is called with the `result` of import operation, a value of `0` indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). ### `app.configureHostResolver(options)` * `options` Object * `enableBuiltInResolver` boolean (optional) - Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. * `secureDnsMode` string (optional) - Can be "off", "automatic" or "secure". Configures the DNS-over-HTTP mode. When "off", no DoH lookups will be performed. When "automatic", DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When "secure", only DoH lookups will be performed. Defaults to "automatic". * `secureDnsServers` string[]&#32;(optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for [some DNS providers][doh-providers], the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list. * `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true. Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order: 1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then 2. the built-in resolver (enabled on macOS only by default), then 3. the system's resolver (e.g. `getaddrinfo`). This can be configured to either restrict usage of non-encrypted DNS (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). It is also possible to enable or disable the built-in resolver. To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user's DNS configuration does not include a provider that supports DoH. ```js app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) ``` This API must be called after the `ready` event is emitted. [doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc [RFC8484 § 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3 ### `app.disableHardwareAcceleration()` Disables hardware acceleration for current app. This method can only be called before app is ready. ### `app.disableDomainBlockingFor3DAPIs()` By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior. This method can only be called before app is ready. ### `app.getAppMetrics()` Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app. ### `app.getGPUFeatureStatus()` Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`. **Note:** This information is only usable after the `gpu-info-update` event is emitted. ### `app.getGPUInfo(infoType)` * `infoType` string - Can be `basic` or `complete`. Returns `Promise<unknown>` For `infoType` equal to `complete`: Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page. For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response: ```js { auxAttributes: { amdSwitchable: true, canSupportThreadedTextureMailbox: false, directComposition: false, directRendering: true, glResetNotificationStrategy: 0, inProcessGpu: true, initializationTime: 0, jpegDecodeAcceleratorSupported: false, optimus: false, passthroughCmdDecoder: false, sandboxed: false, softwareRendering: false, supportsOverlays: false, videoDecodeAcceleratorFlags: 0 }, gpuDevice: [{ active: true, deviceId: 26657, vendorId: 4098 }, { active: false, deviceId: 3366, vendorId: 32902 }], machineModelName: 'MacBookPro', machineModelVersion: '11.5' } ``` Using `basic` should be preferred if only basic information like `vendorId` or `deviceId` is needed. ### `app.setBadgeCount([count])` _Linux_ _macOS_ * `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display. Returns `boolean` - Whether the call succeeded. Sets the counter badge for current app. Setting the count to `0` will hide the badge. On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. ### `app.getBadgeCount()` _Linux_ _macOS_ Returns `Integer` - The current value displayed in the counter badge. ### `app.isUnityRunning()` _Linux_ Returns `boolean` - Whether the current desktop environment is Unity launcher. ### `app.getLoginItemSettings([options])` _macOS_ _Windows_ * `options` Object (optional) * `path` string (optional) _Windows_ - The executable path to compare against. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to compare against. Defaults to an empty array. If you provided `path` and `args` options to `app.setLoginItemSettings`, then you need to pass the same arguments here for `openAtLogin` to be set correctly. Returns `Object`: * `openAtLogin` boolean - `true` if the app is set to open at login. * `openAsHidden` boolean _macOS_ - `true` if the app is set to open as hidden at login. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login automatically. This setting is not available on [MAS builds][mas-builds]. * `wasOpenedAsHidden` boolean _macOS_ - `true` if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on [MAS builds][mas-builds]. * `restoreState` boolean _macOS_ - `true` if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on [MAS builds][mas-builds]. * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments. * `launchItems` Object[] _Windows_ * `name` string _Windows_ - name value of a registry entry. * `path` string _Windows_ - The executable to an app that corresponds to a registry entry. * `args` string[] _Windows_ - the command-line arguments to pass to the executable. * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings. ### `app.setLoginItemSettings(settings)` _macOS_ _Windows_ * `settings` Object * `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove the app as a login item. Defaults to `false`. * `openAsHidden` boolean (optional) _macOS_ - `true` to open the app as hidden. Defaults to `false`. The user can edit this setting from the System Preferences so `app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app is opened to know the current value. This setting is not available on [MAS builds][mas-builds]. * `path` string (optional) _Windows_ - The executable to launch at login. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes. * `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings. Defaults to `true`. * `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId(). Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], you'll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example: ``` javascript const appFolder = path.dirname(process.execPath) const updateExe = path.resolve(appFolder, '..', 'Update.exe') const exeName = path.basename(process.execPath) app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: [ '--processStart', `"${exeName}"`, '--process-start-args', `"--hidden"` ] }) ``` ### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_ Returns `boolean` - `true` if Chrome's accessibility support is enabled, `false` otherwise. This API will return `true` if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_ * `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.showAboutPanel()` Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously. ### `app.setAboutPanelOptions(options)` * `options` Object * `applicationName` string (optional) - The app's name. * `applicationVersion` string (optional) - The app's version. * `copyright` string (optional) - Copyright information. * `version` string (optional) _macOS_ - The app's build version number. * `credits` string (optional) _macOS_ _Windows_ - Credit information. * `authors` string[] (optional) _Linux_ - List of app authors. * `website` string (optional) _Linux_ - The app's website. * `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults. If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information. ### `app.isEmojiPanelSupported()` Returns `boolean` - whether or not the current OS version allows for native emoji pickers. ### `app.showEmojiPanel()` _macOS_ _Windows_ Show the platform's native emoji picker. ### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_ * `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods. Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted. ```js // Start accessing the file. const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(data) // You can now access the file outside of the sandbox 🎉 // Remember to stop accessing the file once you've finished with it. stopAccessingSecurityScopedResource() ``` Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works. ### `app.enableSandbox()` Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in WebPreferences. This method can only be called before app is ready. ### `app.isInApplicationsFolder()` _macOS_ Returns `boolean` - Whether the application is currently running from the systems Application folder. Use in combination with `app.moveToApplicationsFolder()` ### `app.moveToApplicationsFolder([options])` _macOS_ * `options` Object (optional) * `conflictHandler` Function\<boolean> (optional) - A handler for potential conflict in move failure. * `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running. Returns `boolean` - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch. No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the [`dialog`](dialog.md) API. **NOTE:** This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong. By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing. For example: ```js app.moveToApplicationsFolder({ conflictHandler: (conflictType) => { if (conflictType === 'exists') { return dialog.showMessageBoxSync({ type: 'question', buttons: ['Halt Move', 'Continue Move'], defaultId: 0, message: 'An app of this name already exists' }) === 1 } } }) ``` Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place. ### `app.isSecureKeyboardEntryEnabled()` _macOS_ Returns `boolean` - whether `Secure Keyboard Entry` is enabled. By default this API will return `false`. ### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_ * `enabled` boolean - Enable or disable `Secure Keyboard Entry` Set the `Secure Keyboard Entry` is enabled in your application. By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes. See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more details. **Note:** Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed. ## Properties ### `app.accessibilitySupportEnabled` _macOS_ _Windows_ A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. **Note:** Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.applicationMenu` A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise. Users can pass a [Menu](menu.md) to set this property. ### `app.badgeCount` _Linux_ _macOS_ An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge. On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher. **Note:** Unity launcher requires a `.desktop` file to work. For more information, please read the [Unity integration documentation][unity-requirement]. **Note:** On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect. ### `app.commandLine` _Readonly_ A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the command line arguments that Chromium uses. ### `app.dock` _macOS_ _Readonly_ A [`Dock`](./dock.md) `| undefined` object that allows you to perform actions on your app icon in the user's dock on macOS. ### `app.isPackaged` _Readonly_ A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments. [tasks]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd378460(v=vs.85).aspx#tasks [app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx [electron-forge]: https://www.electronforge.io/ [electron-packager]: https://github.com/electron/electron-packager [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 [LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/library/mac/documentation/Carbon/Reference/LaunchServicesReference/#//apple_ref/c/func/LSCopyDefaultHandlerForURLScheme [handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html [activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType [unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [mas-builds]: ../tutorial/mac-app-store-submission-guide.md [Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows [JumpListBeginListMSDN]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378398(v=vs.85).aspx [about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc ### `app.name` A `string` property that indicates the current application's name, which is the name in the application's `package.json` file. Usually the `name` field of `package.json` is a short lowercase name, according to the npm modules spec. You should usually also specify a `productName` field, which is your application's full capitalized name, and which will be preferred over `name` by Electron. ### `app.userAgentFallback` A `string` which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the `webContents` or `session` level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used. ### `app.runningUnderRosettaTranslation` _macOS_ _Readonly_ _Deprecated_ A `boolean` which when `true` indicates that the app is currently running under the [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)). You can use this property to prompt users to download the arm64 version of your application when they are running the x64 version under Rosetta incorrectly. **Deprecated:** This property is superceded by the `runningUnderARM64Translation` property which detects when the app is being translated to ARM64 in both macOS and Windows. ### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_ A `boolean` which when `true` indicates that the app is currently running under an ARM64 translator (like the macOS [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)) or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)). You can use this property to prompt users to download the arm64 version of your application when they are mistakenly running the x64 version under Rosetta or WOW.
closed
electron/electron
https://github.com/electron/electron
37,476
[Bug]: BrowserWindow.previewFile causes window to not update (appearing frozen)
### 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 23.1.1, 24.0.0-alpha.6, 25.0.0-nightly-20230301 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content should update/respond normally. ### Actual Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content stops updating visually. The window isn't completely frozen though, as javascript is still running and clicking on the page initiates event handlers. Timers seem to fire more slowly, however. ### Testcase Gist URL https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1 ### Additional Information The [testcase fiddle](https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1) updates a button's text to a random string every 10 milliseconds, queries the button's text, and prints it to the console. This video shows that after opening a .log file in Console.app via `BrowserWindow.previewFile`, the button text stops visually updating in the window, but it does update as shown in the devtools console. And clicking on the button causes a console message to be logged as well. https://www.loom.com/share/4fbd0f43c61b47f3ab00acf64d2a196f This test case uses Console.app, but we have users also reporting this issue for opening .pdf files in Acrobat Pro. It doesn't reproduce for me with .txt files opening TextEdit. Reproducing the bug also seems to require that the window not be in the default position. It might also require moving the other application window (Console.app) after it's opened.
https://github.com/electron/electron/issues/37476
https://github.com/electron/electron/pull/37530
e480cb7103df6702d0364cf76d1f20724efc49dc
bf1cc1aeb2a55a07d8ed794df1e6a630221bd69a
2023-03-02T23:41:22Z
c++
2023-03-14T13:41:34Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" #import <objc/message.h> #import <objc/runtime.h> namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; - (int64_t)_resizeDirectionForMouseLocation:(CGPoint)location; @end #if IS_MAS_BUILD() // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm @interface NSView (CRFrameViewAdditions) - (void)cr_mouseDownOnFrameView:(NSEvent*)event; @end typedef void (*MouseDownImpl)(id, SEL, NSEvent*); namespace { MouseDownImpl g_nsthemeframe_mousedown; MouseDownImpl g_nsnextstepframe_mousedown; } // namespace // This class is never instantiated, it's just a container for our swizzled // mouseDown method. @interface SwizzledMouseDownHolderClass : NSView @end @implementation SwizzledMouseDownHolderClass - (void)swiz_nsthemeframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) [self cr_mouseDownOnFrameView:event]; g_nsthemeframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsnextstepframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) { [self cr_mouseDownOnFrameView:event]; } g_nsnextstepframe_mousedown(self, @selector(mouseDown:), event); } } @end namespace { void SwizzleMouseDown(NSView* frame_view, SEL swiz_selector, MouseDownImpl* orig_impl) { Method original_mousedown = class_getInstanceMethod([frame_view class], @selector(mouseDown:)); *orig_impl = (MouseDownImpl)method_getImplementation(original_mousedown); Method new_mousedown = class_getInstanceMethod( [SwizzledMouseDownHolderClass class], swiz_selector); method_setImplementation(original_mousedown, method_getImplementation(new_mousedown)); } } // namespace #endif // IS_MAS_BUILD @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { #if IS_MAS_BUILD() // The first time we create a frameless window, we swizzle the // implementation of -[NSNextStepFrame mouseDown:], replacing it with our // own. // This is only necessary on MAS where we can't directly refer to // NSNextStepFrame or NSThemeFrame, as they are private APIs. // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm for // the non-MAS-compatible way of doing this. if (styleMask & NSWindowStyleMaskTitled) { if (!g_nsthemeframe_mousedown) { NSView* theme_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([theme_frame class]), "NSThemeFrame") == 0) << "Expected NSThemeFrame but was " << class_getName([theme_frame class]); SwizzleMouseDown(theme_frame, @selector(swiz_nsthemeframe_mouseDown:), &g_nsthemeframe_mousedown); } } else { if (!g_nsnextstepframe_mousedown) { NSView* nextstep_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([nextstep_frame class]), "NSNextStepFrame") == 0) << "Expected NSNextStepFrame but was " << class_getName([nextstep_frame class]); SwizzleMouseDown(nextstep_frame, @selector(swiz_nsnextstepframe_mouseDown:), &g_nsnextstepframe_mousedown); } } #endif // IS_MAS_BUILD shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)swipeWithEvent:(NSEvent*)event { if (event.deltaY == 1.0) { shell_->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell_->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell_->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell_->NotifyWindowSwipe("left"); } } - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [[children mutableCopy] autorelease]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = [self delegate]; panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = nil; panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
37,476
[Bug]: BrowserWindow.previewFile causes window to not update (appearing frozen)
### 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 23.1.1, 24.0.0-alpha.6, 25.0.0-nightly-20230301 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content should update/respond normally. ### Actual Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content stops updating visually. The window isn't completely frozen though, as javascript is still running and clicking on the page initiates event handlers. Timers seem to fire more slowly, however. ### Testcase Gist URL https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1 ### Additional Information The [testcase fiddle](https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1) updates a button's text to a random string every 10 milliseconds, queries the button's text, and prints it to the console. This video shows that after opening a .log file in Console.app via `BrowserWindow.previewFile`, the button text stops visually updating in the window, but it does update as shown in the devtools console. And clicking on the button causes a console message to be logged as well. https://www.loom.com/share/4fbd0f43c61b47f3ab00acf64d2a196f This test case uses Console.app, but we have users also reporting this issue for opening .pdf files in Acrobat Pro. It doesn't reproduce for me with .txt files opening TextEdit. Reproducing the bug also seems to require that the window not be in the default position. It might also require moving the other application window (Console.app) after it's opened.
https://github.com/electron/electron/issues/37476
https://github.com/electron/electron/pull/37530
e480cb7103df6702d0364cf76d1f20724efc49dc
bf1cc1aeb2a55a07d8ed794df1e6a630221bd69a
2023-03-02T23:41:22Z
c++
2023-03-14T13:41:34Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); w.setKiosk(true); await setTimeout(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch !== 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,476
[Bug]: BrowserWindow.previewFile causes window to not update (appearing frozen)
### 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 23.1.1, 24.0.0-alpha.6, 25.0.0-nightly-20230301 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content should update/respond normally. ### Actual Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content stops updating visually. The window isn't completely frozen though, as javascript is still running and clicking on the page initiates event handlers. Timers seem to fire more slowly, however. ### Testcase Gist URL https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1 ### Additional Information The [testcase fiddle](https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1) updates a button's text to a random string every 10 milliseconds, queries the button's text, and prints it to the console. This video shows that after opening a .log file in Console.app via `BrowserWindow.previewFile`, the button text stops visually updating in the window, but it does update as shown in the devtools console. And clicking on the button causes a console message to be logged as well. https://www.loom.com/share/4fbd0f43c61b47f3ab00acf64d2a196f This test case uses Console.app, but we have users also reporting this issue for opening .pdf files in Acrobat Pro. It doesn't reproduce for me with .txt files opening TextEdit. Reproducing the bug also seems to require that the window not be in the default position. It might also require moving the other application window (Console.app) after it's opened.
https://github.com/electron/electron/issues/37476
https://github.com/electron/electron/pull/37530
e480cb7103df6702d0364cf76d1f20724efc49dc
bf1cc1aeb2a55a07d8ed794df1e6a630221bd69a
2023-03-02T23:41:22Z
c++
2023-03-14T13:41:34Z
shell/browser/ui/cocoa/electron_ns_window.mm
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/native_window_mac.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "ui/base/cocoa/window_size_constants.h" #import <objc/message.h> #import <objc/runtime.h> namespace electron { int ScopedDisableResize::disable_resize_ = 0; } // namespace electron @interface NSWindow (PrivateAPI) - (NSImage*)_cornerMask; - (int64_t)_resizeDirectionForMouseLocation:(CGPoint)location; @end #if IS_MAS_BUILD() // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm @interface NSView (CRFrameViewAdditions) - (void)cr_mouseDownOnFrameView:(NSEvent*)event; @end typedef void (*MouseDownImpl)(id, SEL, NSEvent*); namespace { MouseDownImpl g_nsthemeframe_mousedown; MouseDownImpl g_nsnextstepframe_mousedown; } // namespace // This class is never instantiated, it's just a container for our swizzled // mouseDown method. @interface SwizzledMouseDownHolderClass : NSView @end @implementation SwizzledMouseDownHolderClass - (void)swiz_nsthemeframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) [self cr_mouseDownOnFrameView:event]; g_nsthemeframe_mousedown(self, @selector(mouseDown:), event); } } - (void)swiz_nsnextstepframe_mouseDown:(NSEvent*)event { if ([self.window respondsToSelector:@selector(shell)]) { electron::NativeWindowMac* shell = (electron::NativeWindowMac*)[(id)self.window shell]; if (shell && !shell->has_frame()) { [self cr_mouseDownOnFrameView:event]; } g_nsnextstepframe_mousedown(self, @selector(mouseDown:), event); } } @end namespace { void SwizzleMouseDown(NSView* frame_view, SEL swiz_selector, MouseDownImpl* orig_impl) { Method original_mousedown = class_getInstanceMethod([frame_view class], @selector(mouseDown:)); *orig_impl = (MouseDownImpl)method_getImplementation(original_mousedown); Method new_mousedown = class_getInstanceMethod( [SwizzledMouseDownHolderClass class], swiz_selector); method_setImplementation(original_mousedown, method_getImplementation(new_mousedown)); } } // namespace #endif // IS_MAS_BUILD @implementation ElectronNSWindow @synthesize acceptsFirstMouse; @synthesize enableLargerThanScreen; @synthesize disableAutoHideCursor; @synthesize disableKeyOrMainWindow; @synthesize vibrantView; @synthesize cornerMask; - (id)initWithShell:(electron::NativeWindowMac*)shell styleMask:(NSUInteger)styleMask { if ((self = [super initWithContentRect:ui::kWindowSizeDeterminedLater styleMask:styleMask backing:NSBackingStoreBuffered defer:NO])) { #if IS_MAS_BUILD() // The first time we create a frameless window, we swizzle the // implementation of -[NSNextStepFrame mouseDown:], replacing it with our // own. // This is only necessary on MAS where we can't directly refer to // NSNextStepFrame or NSThemeFrame, as they are private APIs. // See components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm for // the non-MAS-compatible way of doing this. if (styleMask & NSWindowStyleMaskTitled) { if (!g_nsthemeframe_mousedown) { NSView* theme_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([theme_frame class]), "NSThemeFrame") == 0) << "Expected NSThemeFrame but was " << class_getName([theme_frame class]); SwizzleMouseDown(theme_frame, @selector(swiz_nsthemeframe_mouseDown:), &g_nsthemeframe_mousedown); } } else { if (!g_nsnextstepframe_mousedown) { NSView* nextstep_frame = [[self contentView] superview]; DCHECK(strcmp(class_getName([nextstep_frame class]), "NSNextStepFrame") == 0) << "Expected NSNextStepFrame but was " << class_getName([nextstep_frame class]); SwizzleMouseDown(nextstep_frame, @selector(swiz_nsnextstepframe_mouseDown:), &g_nsnextstepframe_mousedown); } } #endif // IS_MAS_BUILD shell_ = shell; } return self; } - (electron::NativeWindowMac*)shell { return shell_; } - (id)accessibilityFocusedUIElement { views::Widget* widget = shell_->widget(); id superFocus = [super accessibilityFocusedUIElement]; if (!widget || shell_->IsFocused()) return superFocus; return nil; } - (NSRect)originalContentRectForFrameRect:(NSRect)frameRect { return [super contentRectForFrameRect:frameRect]; } - (NSTouchBar*)makeTouchBar { if (shell_->touch_bar()) return [shell_->touch_bar() makeTouchBar]; else return nil; } // NSWindow overrides. - (void)swipeWithEvent:(NSEvent*)event { if (event.deltaY == 1.0) { shell_->NotifyWindowSwipe("up"); } else if (event.deltaX == -1.0) { shell_->NotifyWindowSwipe("right"); } else if (event.deltaY == -1.0) { shell_->NotifyWindowSwipe("down"); } else if (event.deltaX == 1.0) { shell_->NotifyWindowSwipe("left"); } } - (void)rotateWithEvent:(NSEvent*)event { shell_->NotifyWindowRotateGesture(event.rotation); } - (NSRect)contentRectForFrameRect:(NSRect)frameRect { if (shell_->has_frame()) return [super contentRectForFrameRect:frameRect]; else return frameRect; } - (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen { // Resizing is disabled. if (electron::ScopedDisableResize::IsResizeDisabled()) return [self frame]; NSRect result = [super constrainFrameRect:frameRect toScreen:screen]; // Enable the window to be larger than screen. if ([self enableLargerThanScreen]) { // If we have a frame, ensure that we only position the window // somewhere where the user can move or resize it (and not // behind the menu bar, for instance) // // If there's no frame, put the window wherever the developer // wanted it to go if (shell_->has_frame()) { result.size = frameRect.size; } else { result = frameRect; } } return result; } - (void)setFrame:(NSRect)windowFrame display:(BOOL)displayViews { // constrainFrameRect is not called on hidden windows so disable adjusting // the frame directly when resize is disabled if (!electron::ScopedDisableResize::IsResizeDisabled()) [super setFrame:windowFrame display:displayViews]; } - (id)accessibilityAttributeValue:(NSString*)attribute { if ([attribute isEqual:NSAccessibilityEnabledAttribute]) return [NSNumber numberWithBool:YES]; if (![attribute isEqualToString:@"AXChildren"]) return [super accessibilityAttributeValue:attribute]; // We want to remove the window title (also known as // NSAccessibilityReparentingCellProxy), which VoiceOver already sees. // * when VoiceOver is disabled, this causes Cmd+C to be used for TTS but // still leaves the buttons available in the accessibility tree. // * when VoiceOver is enabled, the full accessibility tree is used. // Without removing the title and with VO disabled, the TTS would always read // the window title instead of using Cmd+C to get the selected text. NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(self.className != %@)", @"NSAccessibilityReparentingCellProxy"]; NSArray* children = [super accessibilityAttributeValue:attribute]; NSMutableArray* mutableChildren = [[children mutableCopy] autorelease]; [mutableChildren filterUsingPredicate:predicate]; return mutableChildren; } - (NSString*)accessibilityTitle { return base::SysUTF8ToNSString(shell_->GetTitle()); } - (BOOL)canBecomeMainWindow { return !self.disableKeyOrMainWindow; } - (BOOL)canBecomeKeyWindow { return !self.disableKeyOrMainWindow; } - (NSView*)frameView { return [[self contentView] superview]; } - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { // By default "Close Window" is always disabled when window has no title, to // support closing a window without title we need to manually do menu item // validation. This code path is used by the "roundedCorners" option. if ([item action] == @selector(performClose:)) return shell_->IsClosable(); return [super validateUserInterfaceItem:item]; } // By overriding this built-in method the corners of the vibrant view (if set) // will be smooth. - (NSImage*)_cornerMask { if (self.vibrantView != nil) { return [self cornerMask]; } else { return [super _cornerMask]; } } // Quicklook methods - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel { return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = [self delegate]; panel.dataSource = static_cast<id<QLPreviewPanelDataSource>>([self delegate]); } - (void)endPreviewPanelControl:(QLPreviewPanel*)panel { panel.delegate = nil; panel.dataSource = nil; } // Custom window button methods - (BOOL)windowShouldClose:(id)sender { return YES; } - (void)performClose:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) { [[self delegate] windowShouldClose:self]; } else if (!([self styleMask] & NSWindowStyleMaskTitled)) { // performClose does not work for windows without title, so we have to // emulate its behavior. This code path is used by "simpleFullscreen" and // "roundedCorners" options. if ([[self delegate] respondsToSelector:@selector(windowShouldClose:)]) { if (![[self delegate] windowShouldClose:self]) return; } else if ([self respondsToSelector:@selector(windowShouldClose:)]) { if (![self windowShouldClose:self]) return; } [self close]; } else if (shell_->is_modal() && shell_->parent() && shell_->IsVisible()) { // We don't want to actually call [window close] here since // we've already called endSheet on the modal sheet. return; } else { [super performClose:sender]; } } - (void)toggleFullScreenMode:(id)sender { bool is_simple_fs = shell_->IsSimpleFullScreen(); bool always_simple_fs = shell_->always_simple_fullscreen(); // If we're in simple fullscreen mode and trying to exit it // we need to ensure we exit it properly to prevent a crash // with NSWindowStyleMaskTitled mode. if (is_simple_fs || always_simple_fs) { shell_->SetSimpleFullScreen(!is_simple_fs); } else { if (shell_->IsVisible()) { // Until 10.13, AppKit would obey a call to -toggleFullScreen: made inside // windowDidEnterFullScreen & windowDidExitFullScreen. Starting in 10.13, // it behaves as though the transition is still in progress and just emits // "not in a fullscreen state" when trying to exit fullscreen in the same // runloop that entered it. To handle this, invoke -toggleFullScreen: // asynchronously. [super performSelector:@selector(toggleFullScreen:) withObject:nil afterDelay:0]; } else { [super toggleFullScreen:sender]; } // Exiting fullscreen causes Cocoa to redraw the NSWindow, which resets // the enabled state for NSWindowZoomButton. We need to persist it. bool maximizable = shell_->IsMaximizable(); shell_->SetMaximizable(maximizable); } } - (void)performMiniaturize:(id)sender { if (shell_->title_bar_style() == electron::NativeWindowMac::TitleBarStyle::kCustomButtonsOnHover) [self miniaturize:self]; else [super performMiniaturize:sender]; } @end
closed
electron/electron
https://github.com/electron/electron
37,476
[Bug]: BrowserWindow.previewFile causes window to not update (appearing frozen)
### 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 23.1.1, 24.0.0-alpha.6, 25.0.0-nightly-20230301 ### What operating system are you using? macOS ### Operating System Version macOS 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version n/a ### Expected Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content should update/respond normally. ### Actual Behavior When using `BrowserWindow.previewFile` and then choosing to open the file from QuickLook, the `BrowserWindow` content stops updating visually. The window isn't completely frozen though, as javascript is still running and clicking on the page initiates event handlers. Timers seem to fire more slowly, however. ### Testcase Gist URL https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1 ### Additional Information The [testcase fiddle](https://gist.github.com/a15492e41ae5c4dacb1152c35bea5cc1) updates a button's text to a random string every 10 milliseconds, queries the button's text, and prints it to the console. This video shows that after opening a .log file in Console.app via `BrowserWindow.previewFile`, the button text stops visually updating in the window, but it does update as shown in the devtools console. And clicking on the button causes a console message to be logged as well. https://www.loom.com/share/4fbd0f43c61b47f3ab00acf64d2a196f This test case uses Console.app, but we have users also reporting this issue for opening .pdf files in Acrobat Pro. It doesn't reproduce for me with .txt files opening TextEdit. Reproducing the bug also seems to require that the window not be in the default position. It might also require moving the other application window (Console.app) after it's opened.
https://github.com/electron/electron/issues/37476
https://github.com/electron/electron/pull/37530
e480cb7103df6702d0364cf76d1f20724efc49dc
bf1cc1aeb2a55a07d8ed794df1e6a630221bd69a
2023-03-02T23:41:22Z
c++
2023-03-14T13:41:34Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import * as os from 'os'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, WebFrameMain } from 'electron/main'; import { emittedUntil, emittedNTimes } from './lib/events-helpers'; import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers'; import { closeWindow, closeAllWindows } from './lib/window-helpers'; import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(fixtures, 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await once(appProcess, 'exit'); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await setTimeout(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await setTimeout(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = once(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = once(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = once(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await once(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = once(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = once(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await once(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await once(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w: BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server: http.Server; let url: string; let postData = null as any; before(async () => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond); }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = once(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = once(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-navigate'); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); await event; w.close(); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame); let initiator: WebFrameMain | undefined; w.webContents.on('will-navigate', (e) => { initiator = e.initiator; }); const subframe = w.webContents.mainFrame.frames[0]; subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true); await once(w.webContents, 'did-navigate'); expect(initiator).not.to.be.undefined(); expect(initiator).to.equal(subframe); }); }); describe('will-redirect event', () => { let server: http.Server; let url: string; before(async () => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); url = (await listen(server)).url; }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', async () => { const event = once(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await event; w.close(); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { const p = once(w, 'focus'); w.show(); await p; expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = once(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = once(w, 'show'); w.show(); await shown; const hidden = once(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = once(w, 'maximize'); const shown = once(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await setTimeout(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = once(w, 'blur'); const isShown = once(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = once(w, 'focus'); const isShown = once(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = once(w3, 'focus'); const isShown1 = once(w1, 'show'); const isShown2 = once(w2, 'show'); const isShown3 = once(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = once(w1, 'closed'); const isClosed2 = once(w2, 'closed'); const isClosed3 = once(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { const p = once(w, 'focus'); w.show(); await p; w.webContents.openDevTools({ mode: 'undocked' }); await once(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = once(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = once(otherWindow, 'show'); const otherWindowFocused = once(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = once(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = once(w, 'focus'); const otherWindowBlurred = once(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = once(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = once(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = once(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = once(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(once(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = once(w, 'resize'); w.setContentBounds(bounds); await resize; await setTimeout(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = once(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = once(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('does not go fullscreen if roundedCorners are enabled', async () => { w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true }); expect(w.fullScreen).to.be.false(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = once(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = once(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = once(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = once(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = once(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = once(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => { const w = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true }); const visible = await w.webContents.executeJavaScript('document.visibilityState'); expect(visible).to.equal('hidden'); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await once(w, 'ready-to-show'); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await once(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w: BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w: BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = once(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w: BrowserWindow; let server: http.Server; let url: string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); url = (await listen(server)).url; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = once(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { afterEach(closeAllWindows); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getWindowButtonPosition(pos)', () => { it('returns null when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition'); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getWindowButtonPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setWindowButtonPosition(pos)', () => { it('resets the position when null is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setWindowButtonPosition(null); expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition'); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setWindowButtonPosition(newPos); expect(w.getWindowButtonPosition()).to.deep.equal(newPos); }); }); // The set/getTrafficLightPosition APIs are deprecated. describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('returns { x: 0, y: 0 } when there is no custom position', () => { const w = new BrowserWindow({ show: false }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('resets the position when { x: 0, y: 0 } is passed', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); w.setTrafficLightPosition({ x: 0, y: 0 }); expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 }); }); it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = once(w.webContents, 'did-attach-webview'); const [, webviewContents] = await once(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise<any>((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); bv1.webContents.destroy(); bv2.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { bv.webContents.destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = once(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = once(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await once(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await once(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await once(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await once(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await once(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await once(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await once(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('exposes full EventEmitter object to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: path.join(fixtures, 'module', 'preload-eventemitter.js') } }); w.loadURL('about:blank'); const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer'); const { EventEmitter } = require('events'); const emitter = new EventEmitter(); const browserEventEmitterProperties = []; let currentObj = emitter; do { browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj)); } while ((currentObj = Object.getPrototypeOf(currentObj))); expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = once(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await once(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await once(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = once(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = once(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = once(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await once(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => once(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = once(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => once(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => once(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await once(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = once(w.webContents, 'did-attach-webview'); const webviewDomReady = once(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = once(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await once(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = once(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via setWindowOpenHandler handlers', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ once(app, 'web-contents-created'), once(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = once(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await once(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.close(); await once(w.webContents, 'before-unload-fired'); w.close(); await once(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = once(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await once(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await once(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await once(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await once(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = once(w, 'show'); w.show(); await shown1; const hidden = once(w, 'hide'); w.hide(); await hidden; const shown2 = once(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = once(w, 'maximize'); const unmaximize = once(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = once(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout().then(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { /* Use temp directory for saving MHTML file since the write handle * gets passed to untrusted process and chromium will deny exec access to * the path. To perform this task, chromium requires that the path is one * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416 */ const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-')); const savePageMHTMLPath = path.join(tmpDir, 'save_page.html'); const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageMHTMLPath, 'MHTML'); expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); } catch {} }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); // TODO(zcbenz): // This test does not run on Linux CI. See: // https://github.com/electron/electron/issues/28699 ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => { const w = new BrowserWindow({}); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); const restore = once(w, 'restore'); w.restore(); await restore; expect(w.isMaximized()).to.equal(true); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = once(w, 'hide'); let shown = once(w, 'show'); const maximize = once(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = once(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = once(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await setTimeout(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await setTimeout(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = once(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await once(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await setTimeout(); w.setFullScreen(false); await once(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = once(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = once(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = once(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = once(two, 'show'); two.show(); await twoShown; setTimeout(500).then(() => two.close()); await once(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = once(one, 'show'); one.show(); await oneShown; setTimeout(500).then(() => one.destroy()); await once(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('can disable and enable a window', () => { const w = new BrowserWindow({ show: false }); w.setEnabled(false); expect(w.isEnabled()).to.be.false('w.isEnabled()'); w.setEnabled(true); expect(w.isEnabled()).to.be.true('!w.isEnabled()'); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = once(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((request, response) => { response.end(); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = once(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = once(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => { it('with functions', () => { it('can be set with ignoreMissionControl constructor option', () => { const w = new BrowserWindow({ show: false, hiddenInMissionControl: true }); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); w.setHiddenInMissionControl(true); expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl'); w.setHiddenInMissionControl(false); expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('should be able to load a URL while transitioning to fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true }); w.loadFile(path.join(fixtures, 'pages', 'c.html')); const load = once(w.webContents, 'did-finish-load'); const enterFS = once(w, 'enter-full-screen'); await Promise.all([enterFS, load]); expect(w.fullScreen).to.be.true(); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await setTimeout(); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = once(w, 'enter-full-screen'); const leaveFullScreen = once(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await setTimeout(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('handles HTML fullscreen transitions when fullscreenable is false', async () => { const w = new BrowserWindow({ fullscreenable: false }); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>((resolve, reject) => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', async () => { enterCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement'); if (!isFS) reject(new Error('Document should have fullscreen element')); checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false')); checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await expect(done).to.eventually.be.fulfilled(); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await setTimeout(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); w.setKiosk(true); await setTimeout(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await setTimeout(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = once(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); // TODO (jkleinsc) renable these tests on mas arm64 ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = once(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = once(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = once(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = once(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = once(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = once(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = once(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await once(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await once(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = once(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await once(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch !== 'x64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.GREEN, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'); await foregroundWindow.loadFile(colorFile); await setTimeout(1000); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true(); expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true(); }); ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: HexColors.PURPLE, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, hasShadow: false, webPreferences: { contextIsolation: false, nodeIntegration: true } }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html')); await once(ipcMain, 'set-transparent'); await setTimeout(); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform === 'darwin')('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: HexColors.BLUE }); w.loadURL('about:blank'); await once(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
shell/browser/api/electron_api_cookies.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_cookies.h" #include <utility> #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "gin/dictionary.h" #include "gin/object_template_builder.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_inclusion_status.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/gurl_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" namespace gin { template <> struct Converter<net::CookieSameSite> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CookieSameSite& val) { switch (val) { case net::CookieSameSite::UNSPECIFIED: return ConvertToV8(isolate, "unspecified"); case net::CookieSameSite::NO_RESTRICTION: return ConvertToV8(isolate, "no_restriction"); case net::CookieSameSite::LAX_MODE: return ConvertToV8(isolate, "lax"); case net::CookieSameSite::STRICT_MODE: return ConvertToV8(isolate, "strict"); } DCHECK(false); return ConvertToV8(isolate, "unknown"); } }; template <> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { gin::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); dict.Set("sameSite", val.SameSite()); return ConvertToV8(isolate, dict).As<v8::Object>(); } }; template <> struct Converter<net::CookieChangeCause> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CookieChangeCause& val) { switch (val) { case net::CookieChangeCause::INSERTED: case net::CookieChangeCause::EXPLICIT: return gin::StringToV8(isolate, "explicit"); case net::CookieChangeCause::OVERWRITE: return gin::StringToV8(isolate, "overwrite"); case net::CookieChangeCause::EXPIRED: return gin::StringToV8(isolate, "expired"); case net::CookieChangeCause::EVICTED: return gin::StringToV8(isolate, "evicted"); case net::CookieChangeCause::EXPIRED_OVERWRITE: return gin::StringToV8(isolate, "expired-overwrite"); default: return gin::StringToV8(isolate, "unknown"); } } }; } // namespace gin namespace electron::api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::Value::Dict& filter, const net::CanonicalCookie& cookie) { const std::string* str; if ((str = filter.FindString("name")) && *str != cookie.Name()) return false; if ((str = filter.FindString("path")) && *str != cookie.Path()) return false; if ((str = filter.FindString("domain")) && !MatchesDomain(*str, cookie.Domain())) return false; absl::optional<bool> secure_filter = filter.FindBool("secure"); if (secure_filter && *secure_filter != cookie.IsSecure()) return false; absl::optional<bool> session_filter = filter.FindBool("session"); if (session_filter && *session_filter == cookie.IsPersistent()) return false; absl::optional<bool> httpOnly_filter = filter.FindBool("httpOnly"); if (httpOnly_filter && *httpOnly_filter != cookie.IsHttpOnly()) return false; return true; } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(base::Value::Dict filter, gin_helper::Promise<net::CookieList> promise, const net::CookieList& cookies) { net::CookieList result; for (const auto& cookie : cookies) { if (MatchesCookie(filter, cookie)) result.push_back(cookie); } promise.Resolve(result); } void FilterCookieWithStatuses( base::Value::Dict filter, gin_helper::Promise<net::CookieList> promise, const net::CookieAccessResultList& list, const net::CookieAccessResultList& excluded_list) { FilterCookies(std::move(filter), std::move(promise), net::cookie_util::StripAccessResults(list)); } // Parse dictionary property to CanonicalCookie time correctly. base::Time ParseTimeProperty(const absl::optional<double>& value) { if (!value) // empty time means ignoring the parameter return base::Time(); if (*value == 0) // FromDoubleT would convert 0 to empty Time return base::Time::UnixEpoch(); return base::Time::FromDoubleT(*value); } std::string InclusionStatusToString(net::CookieInclusionStatus status) { if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY)) return "Failed to create httponly cookie"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_SECURE_ONLY)) return "Cannot create a secure cookie from an insecure URL"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE)) return "Failed to parse cookie"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN)) return "Failed to get cookie domain"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX)) return "Failed because the cookie violated prefix rules."; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME)) return "Cannot set cookie for current scheme"; return "Setting cookie failed"; } std::string StringToCookieSameSite(const std::string* str_ptr, net::CookieSameSite* same_site) { if (!str_ptr) { *same_site = net::CookieSameSite::LAX_MODE; return ""; } const std::string& str = *str_ptr; if (str == "unspecified") { *same_site = net::CookieSameSite::UNSPECIFIED; } else if (str == "no_restriction") { *same_site = net::CookieSameSite::NO_RESTRICTION; } else if (str == "lax") { *same_site = net::CookieSameSite::LAX_MODE; } else if (str == "strict") { *same_site = net::CookieSameSite::STRICT_MODE; } else { return "Failed to convert '" + str + "' to an appropriate cookie same site value"; } return ""; } } // namespace gin::WrapperInfo Cookies::kWrapperInfo = {gin::kEmbedderNativeGin}; Cookies::Cookies(v8::Isolate* isolate, ElectronBrowserContext* browser_context) : browser_context_(browser_context) { cookie_change_subscription_ = browser_context_->cookie_change_notifier()->RegisterCookieChangeCallback( base::BindRepeating(&Cookies::OnCookieChanged, base::Unretained(this))); } Cookies::~Cookies() = default; v8::Local<v8::Promise> Cookies::Get(v8::Isolate* isolate, const gin_helper::Dictionary& filter) { gin_helper::Promise<net::CookieList> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); base::Value::Dict dict; gin::ConvertFromV8(isolate, filter.GetHandle(), &dict); std::string url; filter.Get("url", &url); if (url.empty()) { manager->GetAllCookies( base::BindOnce(&FilterCookies, std::move(dict), std::move(promise))); } else { net::CookieOptions options; options.set_include_httponly(); options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::MakeInclusive()); options.set_do_not_update_access_time(); manager->GetCookieList(GURL(url), options, net::CookiePartitionKeyCollection::Todo(), base::BindOnce(&FilterCookieWithStatuses, std::move(dict), std::move(promise))); } return handle; } v8::Local<v8::Promise> Cookies::Remove(v8::Isolate* isolate, const GURL& url, const std::string& name) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto cookie_deletion_filter = network::mojom::CookieDeletionFilter::New(); cookie_deletion_filter->url = url; cookie_deletion_filter->cookie_name = name; auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->DeleteCookies( std::move(cookie_deletion_filter), base::BindOnce( [](gin_helper::Promise<void> promise, uint32_t num_deleted) { gin_helper::Promise<void>::ResolvePromise(std::move(promise)); }, std::move(promise))); return handle; } v8::Local<v8::Promise> Cookies::Set(v8::Isolate* isolate, base::Value::Dict details) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); const std::string* url_string = details.FindString("url"); if (!url_string) { promise.RejectWithErrorMessage("Missing required option 'url'"); return handle; } const std::string* name = details.FindString("name"); const std::string* value = details.FindString("value"); const std::string* domain = details.FindString("domain"); const std::string* path = details.FindString("path"); bool http_only = details.FindBool("httpOnly").value_or(false); const std::string* same_site_string = details.FindString("sameSite"); net::CookieSameSite same_site; std::string error = StringToCookieSameSite(same_site_string, &same_site); if (!error.empty()) { promise.RejectWithErrorMessage(error); return handle; } bool secure = details.FindBool("secure").value_or( same_site == net::CookieSameSite::NO_RESTRICTION); bool same_party = details.FindBool("sameParty") .value_or(secure && same_site != net::CookieSameSite::STRICT_MODE); GURL url(url_string ? *url_string : ""); if (!url.is_valid()) { promise.RejectWithErrorMessage( InclusionStatusToString(net::CookieInclusionStatus( net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN))); return handle; } auto canonical_cookie = net::CanonicalCookie::CreateSanitizedCookie( url, name ? *name : "", value ? *value : "", domain ? *domain : "", path ? *path : "", ParseTimeProperty(details.FindDouble("creationDate")), ParseTimeProperty(details.FindDouble("expirationDate")), ParseTimeProperty(details.FindDouble("lastAccessDate")), secure, http_only, same_site, net::COOKIE_PRIORITY_DEFAULT, same_party, absl::nullopt); if (!canonical_cookie || !canonical_cookie->IsCanonical()) { promise.RejectWithErrorMessage( InclusionStatusToString(net::CookieInclusionStatus( net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE))); return handle; } net::CookieOptions options; if (http_only) { options.set_include_httponly(); } options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::MakeInclusive()); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->SetCanonicalCookie( *canonical_cookie, url, options, base::BindOnce( [](gin_helper::Promise<void> promise, net::CookieAccessResult r) { if (r.status.IsInclude()) { promise.Resolve(); } else { promise.RejectWithErrorMessage(InclusionStatusToString(r.status)); } }, std::move(promise))); return handle; } v8::Local<v8::Promise> Cookies::FlushStore(v8::Isolate* isolate) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->FlushCookieStore(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Cookies::OnCookieChanged(const net::CookieChangeInfo& change) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); Emit("changed", gin::ConvertToV8(isolate, change.cookie), gin::ConvertToV8(isolate, change.cause), gin::ConvertToV8(isolate, change.cause != net::CookieChangeCause::INSERTED)); } // static gin::Handle<Cookies> Cookies::Create(v8::Isolate* isolate, ElectronBrowserContext* browser_context) { return gin::CreateHandle(isolate, new Cookies(isolate, browser_context)); } gin::ObjectTemplateBuilder Cookies::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Cookies>::GetObjectTemplateBuilder( isolate) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set) .SetMethod("flushStore", &Cookies::FlushStore); } const char* Cookies::GetTypeName() { return "Cookies"; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
spec/api-net-spec.ts
import { expect } from 'chai'; import * as dns from 'dns'; import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions, protocol } from 'electron/main'; import * as http from 'http'; import * as url from 'url'; import * as path from 'path'; import { Socket } from 'net'; import { defer, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; // See https://github.com/nodejs/node/issues/40702. dns.setDefaultResultOrder('ipv4first'); const kOneKiloByte = 1024; const kOneMegaByte = kOneKiloByte * kOneKiloByte; function randomBuffer (size: number, start: number = 0, end: number = 255) { const range = 1 + end - start; const buffer = Buffer.allocUnsafe(size); for (let i = 0; i < size; ++i) { buffer[i] = start + Math.floor(Math.random() * range); } return buffer; } function randomString (length: number) { const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0)); return buffer.toString(); } async function getResponse (urlRequest: Electron.ClientRequest) { return new Promise<Electron.IncomingMessage>((resolve, reject) => { urlRequest.on('error', reject); urlRequest.on('abort', reject); urlRequest.on('response', (response) => resolve(response)); urlRequest.end(); }); } async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) { return (await collectStreamBodyBuffer(response)).toString(); } function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) { return new Promise<Buffer>((resolve, reject) => { response.on('error', reject); (response as NodeJS.EventEmitter).on('aborted', reject); const data: Buffer[] = []; response.on('data', (chunk) => data.push(chunk)); response.on('end', (chunk?: Buffer) => { if (chunk) data.push(chunk); resolve(Buffer.concat(data)); }); }); } async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> { const server = http.createServer((request, response) => { fn(request, response); // don't close if a redirect was returned if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) { n--; server.close(); } }); const sockets: Socket[] = []; server.on('connection', s => sockets.push(s)); defer(() => { server.close(); sockets.forEach(s => s.destroy()); }); return (await listen(server)).url; } function respondOnce (fn: http.RequestListener) { return respondNTimes(fn, 1); } let routeFailure = false; respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => { return respondNTimes((request, response) => { if (Object.prototype.hasOwnProperty.call(routes, request.url || '')) { (async () => { await Promise.resolve(routes[request.url || ''](request, response)); })().catch((err) => { routeFailure = true; console.error('Route handler failed, this is probably why your test failed', err); response.statusCode = 500; response.end(); }); } else { response.statusCode = 500; response.end(); expect.fail(`Unexpected URL: ${request.url}`); } }, n); }; respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1); respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => { return respondNTimes.toRoutes({ [url]: fn }, n); }; respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1); respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => { const requestUrl = '/requestUrl'; return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`); }; respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1); describe('net module', () => { beforeEach(() => { routeFailure = false; }); afterEach(async function () { await session.defaultSession.clearCache(); if (routeFailure && this.test) { if (!this.test.isFailed()) { throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error'); } } }); describe('HTTP basics', () => { it('should be able to issue a basic GET request', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('GET'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to issue a basic POST request', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('POST'); response.end(); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should fetch correct data in a GET request', async () => { const expectedBodyData = 'Hello World!'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('GET'); response.end(expectedBodyData); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); const body = await collectStreamBody(response); expect(body).to.equal(expectedBodyData); }); it('should post the correct data in a POST request', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; const serverUrl = await respondOnce.toSingleURL(async (request, response) => { postedBodyData = await collectStreamBody(request); response.end(); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(postedBodyData).to.equal(bodyData); }); it('a 307 redirected POST request preserves the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; let methodAfterRedirect: string | undefined; const serverUrl = await respondNTimes.toRoutes({ '/redirect': (req, res) => { res.statusCode = 307; res.setHeader('location', serverUrl); return res.end(); }, '/': async (req, res) => { methodAfterRedirect = req.method; postedBodyData = await collectStreamBody(req); res.end(); } }, 2); const urlRequest = net.request({ method: 'POST', url: serverUrl + '/redirect' }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(methodAfterRedirect).to.equal('POST'); expect(postedBodyData).to.equal(bodyData); }); it('a 302 redirected POST request DOES NOT preserve the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; let methodAfterRedirect: string | undefined; const serverUrl = await respondNTimes.toRoutes({ '/redirect': (req, res) => { res.statusCode = 302; res.setHeader('location', serverUrl); return res.end(); }, '/': async (req, res) => { methodAfterRedirect = req.method; postedBodyData = await collectStreamBody(req); res.end(); } }, 2); const urlRequest = net.request({ method: 'POST', url: serverUrl + '/redirect' }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(methodAfterRedirect).to.equal('GET'); expect(postedBodyData).to.equal(''); }); it('should support chunked encoding', async () => { let receivedRequest: http.IncomingMessage = null as any; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.chunkedEncoding = true; receivedRequest = request; request.on('data', (chunk: Buffer) => { response.write(chunk); }); request.on('end', (chunk: Buffer) => { response.end(chunk); }); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); let chunkIndex = 0; const chunkCount = 100; let sent = Buffer.alloc(0); urlRequest.chunkedEncoding = true; while (chunkIndex < chunkCount) { chunkIndex += 1; const chunk = randomBuffer(kOneKiloByte); sent = Buffer.concat([sent, chunk]); urlRequest.write(chunk); } const response = await getResponse(urlRequest); expect(receivedRequest.method).to.equal('POST'); expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked'); expect(receivedRequest.headers['content-length']).to.equal(undefined); expect(response.statusCode).to.equal(200); const received = await collectStreamBodyBuffer(response); expect(sent.equals(received)).to.be.true(); expect(chunkIndex).to.be.equal(chunkCount); }); for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) { describe(`authentication when ${JSON.stringify(extraOptions)}`, () => { it('should emit the login event when 401', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200).end('ok'); }); let loginAuthInfo: Electron.AuthInfo; const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { loginAuthInfo = authInfo; cb(user, pass); }); const response = await getResponse(request); expect(response.statusCode).to.equal(200); expect(loginAuthInfo!.realm).to.equal('Foo'); expect(loginAuthInfo!.scheme).to.equal('basic'); }); it('should receive 401 response when cancelling authentication', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }); response.end('unauthenticated'); } else { response.writeHead(200).end('ok'); } }); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { cb(); }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(401); expect(body).to.equal('unauthenticated'); }); it('should share credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondNTimes.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const bw = new BrowserWindow({ show: false }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL(serverUrl); bw.close(); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); let logInCount = 0; request.on('login', () => { logInCount++; }); const response = await getResponse(request); await collectStreamBody(response); expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached'); }); it('should share proxy credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const proxyUrl = await respondNTimes((request, response) => { if (!request.headers['proxy-authorization']) { return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`); await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' }); const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL('http://127.0.0.1:9999'); bw.close(); const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions }); let logInCount = 0; request.on('login', () => { logInCount++; }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(200); expect(body).to.equal('ok'); expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached'); }); it('should upload body when 401', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200); request.on('data', (chunk) => response.write(chunk)); request.on('end', () => response.end()); }); const requestData = randomString(kOneKiloByte); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { cb(user, pass); }); request.write(requestData); const response = await getResponse(request); const responseData = await collectStreamBody(response); expect(responseData).to.equal(requestData); }); }); } describe('authentication when {"credentials":"omit"}', () => { it('should not emit the login event when 401', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200).end('ok'); }); const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' }); request.on('login', () => { expect.fail('unexpected login event'); }); const response = await getResponse(request); expect(response.statusCode).to.equal(401); expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"'); }); it('should not share credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondNTimes.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const bw = new BrowserWindow({ show: false }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL(serverUrl); bw.close(); const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' }); request.on('login', () => { expect.fail(); }); const response = await getResponse(request); expect(response.statusCode).to.equal(401); expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"'); }); it('should share proxy credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const proxyUrl = await respondNTimes((request, response) => { if (!request.headers['proxy-authorization']) { return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`); await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' }); const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL('http://127.0.0.1:9999'); bw.close(); const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' }); request.on('login', () => { expect.fail(); }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(200); expect(body).to.equal('ok'); }); }); }); describe('ClientRequest API', () => { it('request/response objects should emit expected events', async () => { const bodyData = randomString(kOneKiloByte); const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(bodyData); }); const urlRequest = net.request(serverUrl); // request close event const closePromise = once(urlRequest, 'close'); // request finish event const finishPromise = once(urlRequest, 'close'); // request "response" event const response = await getResponse(urlRequest); response.on('error', (error: Error) => { expect(error).to.be.an('Error'); }); const statusCode = response.statusCode; expect(statusCode).to.equal(200); // response data event // respond end event const body = await collectStreamBody(response); expect(body).to.equal(bodyData); urlRequest.on('error', (error) => { expect(error).to.be.an('Error'); }); await Promise.all([closePromise, finishPromise]); }); it('should be able to set a custom HTTP request header before first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); urlRequest.write(''); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to set a non-string object as a header value', async () => { const customHeaderName = 'Some-Integer-Value'; const customHeaderValue = 900; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString()); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue as any); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); urlRequest.write(''); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not change the case of header name', async () => { const customHeaderName = 'X-Header-Name'; const customHeaderValue = 'value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString()); expect(request.rawHeaders.includes(customHeaderName)).to.equal(true); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.write(''); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not be able to set a custom HTTP request header after first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.write(''); expect(() => { urlRequest.setHeader(customHeaderName, customHeaderValue); }).to.throw(); expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to remove a custom HTTP request header before first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.removeHeader(customHeaderName); expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined); urlRequest.write(''); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not be able to remove a custom HTTP request header after first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.write(''); expect(() => { urlRequest.removeHeader(customHeaderName); }).to.throw(); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should keep the order of headers', async () => { const customHeaderNameA = 'X-Header-100'; const customHeaderNameB = 'X-Header-200'; const serverUrl = await respondOnce.toSingleURL((request, response) => { const headerNames = Array.from(Object.keys(request.headers)); const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase()); const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase()); expect(headerBIndex).to.be.below(headerAIndex); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderNameB, 'b'); urlRequest.setHeader(customHeaderNameA, 'a'); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to set cookie header line', async () => { const cookieHeaderName = 'Cookie'; const cookieHeaderValue = 'test=12345'; const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`); const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); await customSession.cookies.set({ url: `${serverUrl}`, name: 'test', value: '11111', expirationDate: 0 }); const urlRequest = net.request({ method: 'GET', url: serverUrl, session: customSession }); urlRequest.setHeader(cookieHeaderName, cookieHeaderValue); expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to receive cookies', async () => { const cookie = ['cookie1', 'cookie2']; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', cookie); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.headers['set-cookie']).to.have.same.members(cookie); }); it('should be able to receive content-type', async () => { const contentType = 'mime/test; charset=test'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('content-type', contentType); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.headers['content-type']).to.equal(contentType); }); it('should not use the sessions cookie store by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', `${request.headers.cookie!}`); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const urlRequest = net.request({ url: serverUrl, session: sess }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal('undefined'); }); for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) { describe(`when ${JSON.stringify(extraOptions)}`, () => { it('should be able to use the sessions cookie store', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', request.headers.cookie!); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`); }); it('should be able to use the sessions cookie store with set-cookie', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', 'foo=bar'); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); let cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(0); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); await collectStreamBody(await getResponse(urlRequest)); cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(1); expect(cookies[0]).to.deep.equal({ name: 'foo', value: 'bar', domain: '127.0.0.1', hostOnly: true, path: '/', secure: false, httpOnly: false, session: true, sameSite: 'unspecified' }); }); ['Lax', 'Strict'].forEach((mode) => { it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => { const serverUrl = await respondNTimes.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', `same=site; SameSite=${mode}`); response.setHeader('x-cookie', `${request.headers.cookie}`); response.end(); }, 2); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); let cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(0); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal('undefined'); await collectStreamBody(response); cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(1); expect(cookies[0]).to.deep.equal({ name: 'same', value: 'site', domain: '127.0.0.1', hostOnly: true, path: '/', secure: false, httpOnly: false, session: true, sameSite: mode.toLowerCase() }); const urlRequest2 = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response2 = await getResponse(urlRequest2); expect(response2.headers['x-cookie']).to.equal('same=site'); }); }); it('should be able to use the sessions cookie store safely across redirects', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { response.statusCode = 302; response.statusMessage = 'Moved'; const newUrl = await respondOnce.toSingleURL((req, res) => { res.statusCode = 200; res.statusMessage = 'OK'; res.setHeader('x-cookie', req.headers.cookie!); res.end(); }); response.setHeader('x-cookie', request.headers.cookie!); response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost')); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookie127Val = `${Date.now()}-127`; const cookieLocalVal = `${Date.now()}-local`; const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost'); expect(localhostUrl).to.not.equal(serverUrl); // cookies with lax or strict same-site settings will not // persist after redirects. no_restriction must be used await Promise.all([ sess.cookies.set({ url: serverUrl, name: 'wild_cookie', sameSite: 'no_restriction', value: cookie127Val }), sess.cookies.set({ url: localhostUrl, name: 'wild_cookie', sameSite: 'no_restriction', value: cookieLocalVal }) ]); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); urlRequest.on('redirect', (status, method, url, headers) => { // The initial redirect response should have received the 127 value here expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`); urlRequest.followRedirect(); }); const response = await getResponse(urlRequest); // We expect the server to have received the localhost value here // The original request was to a 127.0.0.1 URL // That request would have the cookie127Val cookie attached // The request is then redirect to a localhost URL (different site) // Because we are using the session cookie store it should do the safe / secure thing // and attach the cookies for the new target domain expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`); }); }); } it('should be able correctly filter out cookies that are secure', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1', secure: true }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', secure: false }) ]); const secureCookies = await sess.cookies.get({ secure: true }); expect(secureCookies).to.have.lengthOf(1); expect(secureCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ secure: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); it('should be able correctly filter out cookies that are session', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1' }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', expirationDate: Math.round(Date.now() / 1000) + 10000 }) ]); const sessionCookies = await sess.cookies.get({ session: true }); expect(sessionCookies).to.have.lengthOf(1); expect(sessionCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ session: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); it('should be able correctly filter out cookies that are httpOnly', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1', httpOnly: true }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', httpOnly: false }) ]); const httpOnlyCookies = await sess.cookies.get({ httpOnly: true }); expect(httpOnlyCookies).to.have.lengthOf(1); expect(httpOnlyCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ httpOnly: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); describe('when {"credentials":"omit"}', () => { it('should not send cookies'); it('should not store cookies'); }); it('should set sec-fetch-site to same-origin for request from same origin', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('same-origin'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-site to same-origin for request with the same origin header', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('same-origin'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.setHeader('Origin', serverUrl); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-site to cross-site for request from other origin', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('cross-site'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: 'https://not-exists.com' }); await collectStreamBody(await getResponse(urlRequest)); }); it('should not send sec-fetch-user header by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers).not.to.have.property('sec-fetch-user'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-user to ?1 if requested', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-user']).to.equal('?1'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.setHeader('sec-fetch-user', '?1'); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-mode to no-cors by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-mode']).to.equal('no-cors'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); ['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => { it(`should set sec-fetch-mode to ${mode} if requested`, async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-mode']).to.equal(mode); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); urlRequest.setHeader('sec-fetch-mode', mode); await collectStreamBody(await getResponse(urlRequest)); }); }); it('should set sec-fetch-dest to empty by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-dest']).to.equal('empty'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); [ 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font', 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet', 'report', 'script', 'serviceworker', 'style', 'track', 'video', 'worker', 'xslt' ].forEach((dest) => { it(`should set sec-fetch-dest to ${dest} if requested`, async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-dest']).to.equal(dest); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); urlRequest.setHeader('sec-fetch-dest', dest); await collectStreamBody(await getResponse(urlRequest)); }); }); it('should be able to abort an HTTP request before first write', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); expect.fail('Unexpected request event'); }); const urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('unexpected response event'); }); const aborted = once(urlRequest, 'abort'); urlRequest.abort(); urlRequest.write(''); urlRequest.end(); await aborted; }); it('it should be able to abort an HTTP request before request end', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL(() => { requestReceivedByServer = true; urlRequest!.abort(); }); let requestAbortEventEmitted = false; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { expect.fail('Unexpected finish event'); }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.on('abort', () => { requestAbortEventEmitted = true; }); const p = once(urlRequest, 'close'); urlRequest.chunkedEncoding = true; urlRequest.write(randomString(kOneKiloByte)); await p; expect(requestReceivedByServer).to.equal(true); expect(requestAbortEventEmitted).to.equal(true); }); it('it should be able to abort an HTTP request after request end and before response', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL((request, response) => { requestReceivedByServer = true; urlRequest!.abort(); process.nextTick(() => { response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); }); let requestFinishEventEmitted = false; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.equal(true); expect(requestReceivedByServer).to.equal(true); }); it('it should be able to abort an HTTP request after response start', async () => { let requestReceivedByServer = false; const serverUrl = await respondOnce.toSingleURL((request, response) => { requestReceivedByServer = true; response.statusCode = 200; response.statusMessage = 'OK'; response.write(randomString(kOneKiloByte)); }); let requestFinishEventEmitted = false; let requestResponseEventEmitted = false; let responseCloseEventEmitted = false; const urlRequest = net.request(serverUrl); urlRequest.on('response', (response) => { requestResponseEventEmitted = true; const statusCode = response.statusCode; expect(statusCode).to.equal(200); response.on('data', () => {}); response.on('end', () => { expect.fail('Unexpected end event'); }); response.on('error', () => { expect.fail('Unexpected error event'); }); response.on('close' as any, () => { responseCloseEventEmitted = true; }); urlRequest.abort(); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event'); expect(requestReceivedByServer).to.be.true('request should be received by the server'); expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted'); expect(responseCloseEventEmitted).to.be.true('response should emit "close" event'); }); it('abort event should be emitted at most once', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL(() => { requestReceivedByServer = true; urlRequest!.abort(); urlRequest!.abort(); }); let requestFinishEventEmitted = false; let abortsEmitted = 0; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.on('abort', () => { abortsEmitted++; }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event'); expect(requestReceivedByServer).to.be.true('request should be received by server'); expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event'); }); it('should allow to read response body from non-2xx response', async () => { const bodyData = randomString(kOneKiloByte); const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 404; response.end(bodyData); }); const urlRequest = net.request(serverUrl); const bodyCheckPromise = getResponse(urlRequest).then(r => { expect(r.statusCode).to.equal(404); return r; }).then(collectStreamBody).then(receivedBodyData => { expect(receivedBodyData.toString()).to.equal(bodyData); }); const eventHandlers = Promise.all([ bodyCheckPromise, once(urlRequest, 'close') ]); urlRequest.end(); await eventHandlers; }); describe('webRequest', () => { afterEach(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); it('Should throw when invalid filters are passed', () => { expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.'); expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.'); }); it('Should not throw when valid filters are passed', () => { expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com/'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.not.throw(); }); it('Requests should be intercepted by webRequest module', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); let requestIsIntercepted = false; session.defaultSession.webRequest.onBeforeRequest( (details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request(`${serverUrl}${requestUrl}`); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); it('should to able to create and intercept a request using a custom session object', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; const customPartitionName = `custom-partition-${Math.random()}`; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); session.defaultSession.webRequest.onBeforeRequest(() => { expect.fail('Request should not be intercepted by the default session'); }); const customSession = session.fromPartition(customPartitionName, { cache: false }); let requestIsIntercepted = false; customSession.webRequest.onBeforeRequest((details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}`, session: customSession }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); it('should to able to create and intercept a request using a custom partition name', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; const customPartitionName = `custom-partition-${Math.random()}`; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); session.defaultSession.webRequest.onBeforeRequest(() => { expect.fail('Request should not be intercepted by the default session'); }); const customSession = session.fromPartition(customPartitionName, { cache: false }); let requestIsIntercepted = false; customSession.webRequest.onBeforeRequest((details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}`, partition: customPartitionName }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); }); it('should throw when calling getHeader without a name', () => { expect(() => { (net.request({ url: 'https://test' }).getHeader as any)(); }).to.throw(/`name` is required for getHeader\(name\)/); expect(() => { net.request({ url: 'https://test' }).getHeader(null as any); }).to.throw(/`name` is required for getHeader\(name\)/); }); it('should throw when calling removeHeader without a name', () => { expect(() => { (net.request({ url: 'https://test' }).removeHeader as any)(); }).to.throw(/`name` is required for removeHeader\(name\)/); expect(() => { net.request({ url: 'https://test' }).removeHeader(null as any); }).to.throw(/`name` is required for removeHeader\(name\)/); }); it('should follow redirect when no redirect handler is provided', async () => { const requestUrl = '/302'; const serverUrl = await respondOnce.toRoutes({ '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}` }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); }); it('should follow redirect chain when no redirect handler is provided', async () => { const serverUrl = await respondOnce.toRoutes({ '/redirectChain': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/302'); response.end(); }, '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}/redirectChain` }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); }); it('should not follow redirect when request is canceled in redirect handler', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.end(); urlRequest.on('redirect', () => { urlRequest.abort(); }); urlRequest.on('error', () => {}); urlRequest.on('response', () => { expect.fail('Unexpected response'); }); await once(urlRequest, 'abort'); }); it('should not follow redirect when mode is error', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }); const urlRequest = net.request({ url: serverUrl, redirect: 'error' }); urlRequest.end(); await once(urlRequest, 'error'); }); it('should follow redirect when handler calls callback', async () => { const serverUrl = await respondOnce.toRoutes({ '/redirectChain': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/302'); response.end(); }, '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' }); const redirects: string[] = []; urlRequest.on('redirect', (status, method, url) => { redirects.push(url); urlRequest.followRedirect(); }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(redirects).to.deep.equal([ `${serverUrl}/302`, `${serverUrl}/200` ]); }); it('should throw if given an invalid session option', () => { expect(() => { net.request({ url: 'https://foo', session: 1 as any }); }).to.throw('`session` should be an instance of the Session class'); }); it('should throw if given an invalid partition option', () => { expect(() => { net.request({ url: 'https://foo', partition: 1 as any }); }).to.throw('`partition` should be a string'); }); it('should be able to create a request with options', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => { expect(request.method).to.equal('GET'); expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const serverUrl = url.parse(serverUrlUnparsed); const options = { port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined, hostname: '127.0.0.1', headers: { [customHeaderName]: customHeaderValue } }; const urlRequest = net.request(options); const response = await getResponse(urlRequest); expect(response.statusCode).to.be.equal(200); await collectStreamBody(response); }); it('should be able to pipe a readable stream into a net request', async () => { const bodyData = randomString(kOneMegaByte); let netRequestReceived = false; let netRequestEnded = false; const [nodeServerUrl, netServerUrl] = await Promise.all([ respondOnce.toSingleURL((request, response) => response.end(bodyData)), respondOnce.toSingleURL((request, response) => { netRequestReceived = true; let receivedBodyData = ''; request.on('data', (chunk) => { receivedBodyData += chunk.toString(); }); request.on('end', (chunk: Buffer | undefined) => { netRequestEnded = true; if (chunk) { receivedBodyData += chunk.toString(); } expect(receivedBodyData).to.be.equal(bodyData); response.end(); }); }) ]); const nodeRequest = http.request(nodeServerUrl); const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse; const netRequest = net.request(netServerUrl); const responsePromise = once(netRequest, 'response'); // TODO(@MarshallOfSound) - FIXME with #22730 nodeResponse.pipe(netRequest as any); const [netResponse] = await responsePromise; expect(netResponse.statusCode).to.equal(200); await collectStreamBody(netResponse); expect(netRequestReceived).to.be.true('net request received'); expect(netRequestEnded).to.be.true('net request ended'); }); it('should report upload progress', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const netRequest = net.request({ url: serverUrl, method: 'POST' }); expect(netRequest.getUploadProgress()).to.have.property('active', false); netRequest.end(Buffer.from('hello')); const [position, total] = await once(netRequest, 'upload-progress'); expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total }); }); it('should emit error event on server socket destroy', async () => { const serverUrl = await respondOnce.toSingleURL((request) => { request.socket.destroy(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); const [error] = await once(urlRequest, 'error'); expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE'); }); it('should emit error event on server request destroy', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.destroy(); response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(randomBuffer(kOneMegaByte)); const [error] = await once(urlRequest, 'error'); expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']); }); it('should not emit any event after close', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); await once(urlRequest, 'close'); await new Promise((resolve, reject) => { ['finish', 'abort', 'close', 'error'].forEach(evName => { urlRequest.on(evName as any, () => { reject(new Error(`Unexpected ${evName} event`)); }); }); setTimeout(50).then(resolve); }); }); it('should remove the referer header when no referrer url specified', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers.referer).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should set the referer header when a referrer url specified', async () => { const referrerURL = 'https://www.electronjs.org/'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers.referer).to.equal(referrerURL); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); // The referrerPolicy must be unsafe-url because the referrer's origin // doesn't match the loaded page. With the default referrer policy // (strict-origin-when-cross-origin), the request will be canceled by the // network service when the referrer header is invalid. // See: // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41 // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698 // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' }); urlRequest.setHeader('referer', referrerURL); urlRequest.end(); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); }); describe('IncomingMessage API', () => { it('response object should implement the IncomingMessage API', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader(customHeaderName, customHeaderValue); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); const headerValue = headers[customHeaderName.toLowerCase()]; expect(headerValue).to.equal(customHeaderValue); const rawHeaders = response.rawHeaders; expect(rawHeaders).to.be.an('array'); expect(rawHeaders[0]).to.equal(customHeaderName); expect(rawHeaders[1]).to.equal(customHeaderValue); const httpVersion = response.httpVersion; expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1); const httpVersionMajor = response.httpVersionMajor; expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1); const httpVersionMinor = response.httpVersionMinor; expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0); await collectStreamBody(response); }); it('should discard duplicate headers', async () => { const includedHeader = 'max-forwards'; const discardableHeader = 'Max-Forwards'; const includedHeaderValue = 'max-fwds-val'; const discardableHeaderValue = 'max-fwds-val-two'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader(discardableHeader, discardableHeaderValue); response.setHeader(includedHeader, includedHeaderValue); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property(includedHeader); expect(headers).to.not.have.property(discardableHeader); expect(headers[includedHeader]).to.equal(includedHeaderValue); await collectStreamBody(response); }); it('should join repeated non-discardable header values with ,', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('referrer-policy', ['first-text', 'second-text']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('referrer-policy'); expect(headers['referrer-policy']).to.equal('first-text, second-text'); await collectStreamBody(response); }); it('should not join repeated discardable header values with ,', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('last-modified', ['yesterday', 'today']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('last-modified'); expect(headers['last-modified']).to.equal('yesterday'); await collectStreamBody(response); }); it('should make set-cookie header an array even if single value', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', 'chocolate-chip'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('set-cookie'); expect(headers['set-cookie']).to.be.an('array'); expect(headers['set-cookie'][0]).to.equal('chocolate-chip'); await collectStreamBody(response); }); it('should keep set-cookie header an array when an array', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('set-cookie'); expect(headers['set-cookie']).to.be.an('array'); expect(headers['set-cookie'][0]).to.equal('chocolate-chip'); expect(headers['set-cookie'][1]).to.equal('oatmeal'); await collectStreamBody(response); }); it('should lowercase header keys', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('HEADER-KEY', ['header-value']); response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']); response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']); response.setHeader('LAST-modified', 'yesterday'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('header-key'); expect(headers).to.have.property('set-cookie'); expect(headers).to.have.property('referrer-policy'); expect(headers).to.have.property('last-modified'); await collectStreamBody(response); }); it('should return correct raw headers', async () => { const customHeaders: [string, string|string[]][] = [ ['HEADER-KEY-ONE', 'header-value-one'], ['set-cookie', 'chocolate-chip'], ['header-key-two', 'header-value-two'], ['referrer-policy', ['first-text', 'second-text']], ['HEADER-KEY-THREE', 'header-value-three'], ['last-modified', ['first-text', 'second-text']], ['header-key-four', 'header-value-four'] ]; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; customHeaders.forEach((headerTuple) => { response.setHeader(headerTuple[0], headerTuple[1]); }); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const rawHeaders = response.rawHeaders; expect(rawHeaders).to.be.an('array'); let rawHeadersIdx = 0; customHeaders.forEach((headerTuple) => { const headerKey = headerTuple[0]; const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]]; headerValues.forEach((headerValue) => { expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey); expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue); rawHeadersIdx += 2; }); }); await collectStreamBody(response); }); it('should be able to pipe a net response into a writable stream', async () => { const bodyData = randomString(kOneKiloByte); let nodeRequestProcessed = false; const [netServerUrl, nodeServerUrl] = await Promise.all([ respondOnce.toSingleURL((request, response) => response.end(bodyData)), respondOnce.toSingleURL(async (request, response) => { const receivedBodyData = await collectStreamBody(request); expect(receivedBodyData).to.be.equal(bodyData); nodeRequestProcessed = true; response.end(); }) ]); const netRequest = net.request(netServerUrl); const netResponse = await getResponse(netRequest); const serverUrl = url.parse(nodeServerUrl); const nodeOptions = { method: 'POST', path: serverUrl.path, port: serverUrl.port }; const nodeRequest = http.request(nodeOptions); const nodeResponsePromise = once(nodeRequest, 'response'); // TODO(@MarshallOfSound) - FIXME with #22730 (netResponse as any).pipe(nodeRequest); const [nodeResponse] = await nodeResponsePromise; netRequest.end(); await collectStreamBody(nodeResponse); expect(nodeRequestProcessed).to.equal(true); }); it('should correctly throttle an incoming stream', async () => { let numChunksSent = 0; const serverUrl = await respondOnce.toSingleURL((request, response) => { const data = randomString(kOneMegaByte); const write = () => { let ok = true; do { numChunksSent++; if (numChunksSent > 30) return; ok = response.write(data); } while (ok); response.once('drain', write); }; write(); }); const urlRequest = net.request(serverUrl); urlRequest.on('response', () => {}); urlRequest.end(); await setTimeout(2000); // TODO(nornagon): I think this ought to max out at 20, but in practice // it seems to exceed that sometimes. This is at 25 to avoid test flakes, // but we should investigate if there's actually something broken here and // if so fix it and reset this to max at 20, and if not then delete this // comment. expect(numChunksSent).to.be.at.most(25); }); }); describe('net.isOnline', () => { it('getter returns boolean', () => { expect(net.isOnline()).to.be.a('boolean'); }); it('property returns boolean', () => { expect(net.online).to.be.a('boolean'); }); }); describe('Stability and performance', () => { it('should free unreferenced, never-started request objects without crash', (done) => { net.request('https://test'); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); done(); }); }); it('should collect on-going requests without crash', async () => { let finishResponse: (() => void) | null = null; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.write(randomString(kOneKiloByte)); finishResponse = () => { response.write(randomString(kOneKiloByte)); response.end(); }; }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); process.nextTick(() => { // Trigger a garbage collection. const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); finishResponse!(); }); await collectStreamBody(response); }); it('should collect unreferenced, ended requests without crash', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const urlRequest = net.request(serverUrl); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); const response = await getResponse(urlRequest); await collectStreamBody(response); }); it('should finish sending data when urlRequest is unreferenced', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); expect(received.length).to.equal(kOneMegaByte); response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.write(randomBuffer(kOneMegaByte)); const response = await getResponse(urlRequest); await collectStreamBody(response); }); it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); const response = await getResponse(urlRequest); await collectStreamBody(response); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); await collectStreamBody(await getResponse(urlRequest)); }); it('should finish sending data when urlRequest is unreferenced', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.write(randomBuffer(kOneMegaByte)); await collectStreamBody(await getResponse(urlRequest)); }); it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); await collectStreamBody(await getResponse(urlRequest)); }); }); describe('non-http schemes', () => { it('should be rejected by net.request', async () => { expect(() => { net.request('file://bar'); }).to.throw('ClientRequest only supports http: and https: protocols'); }); it('should be rejected by net.request when passed in url:', async () => { expect(() => { net.request({ url: 'file://bar' }); }).to.throw('ClientRequest only supports http: and https: protocols'); }); }); describe('net.fetch', () => { // NB. there exist much more comprehensive tests for fetch() in the form of // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch // It's possible to run these tests against net.fetch(), but the test // harness to do so is quite complex and hasn't been munged to smoothly run // inside the Electron test runner yet. // // In the meantime, here are some tests for basic functionality and // Electron-specific behavior. describe('basic', () => { it('can fetch http urls', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end('test'); }); const resp = await net.fetch(serverUrl); expect(resp.ok).to.be.true(); expect(await resp.text()).to.equal('test'); }); it('can upload a string body', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.on('data', chunk => response.write(chunk)); request.on('end', () => response.end()); }); const resp = await net.fetch(serverUrl, { method: 'POST', body: 'anchovies' }); expect(await resp.text()).to.equal('anchovies'); }); it('can read response as an array buffer', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.on('data', chunk => response.write(chunk)); request.on('end', () => response.end()); }); const resp = await net.fetch(serverUrl, { method: 'POST', body: 'anchovies' }); expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies'); }); it('can read response as form data', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.setHeader('content-type', 'application/x-www-form-urlencoded'); response.end('foo=bar'); }); const resp = await net.fetch(serverUrl); const result = await resp.formData(); expect(result.get('foo')).to.equal('bar'); }); it('should be able to use a session cookie store', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', request.headers.cookie!); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const response = await sess.fetch(serverUrl, { credentials: 'include' }); expect(response.headers.get('x-cookie')).to.equal(`wild_cookie=${cookieVal}`); }); it('should reject promise on DNS failure', async () => { const r = net.fetch('https://i.do.not.exist'); await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/); }); it('should reject body promise when stream fails', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.write('first chunk'); setTimeout().then(() => response.destroy()); }); const r = await net.fetch(serverUrl); expect(r.status).to.equal(200); await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/); }); }); it('can request file:// URLs', async () => { const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()); expect(resp.ok).to.be.true(); // trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA expect((await resp.text()).trimRight()).to.equal('hello world'); }); it('can make requests to custom protocols', async () => { protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const body = await net.fetch('electron-test://foo').then(r => r.text()); expect(body).to.equal('hello electron-test://foo'); }); it('runs through intercept handlers', async () => { protocol.interceptStringProtocol('http', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.uninterceptProtocol('http'); }); const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('hello http://foo/'); }); it('file: runs through intercept handlers', async () => { protocol.interceptStringProtocol('file', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.uninterceptProtocol('file'); }); const body = await net.fetch('file://foo').then(r => r.text()); expect(body).to.equal('hello file://foo/'); }); it('can be redirected', async () => { protocol.interceptStringProtocol('file', (req, cb) => { cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); }); defer(() => { protocol.uninterceptProtocol('file'); }); protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const body = await net.fetch('file://foo').then(r => r.text()); expect(body).to.equal('hello electron-test://bar'); }); it('should not follow redirect when redirect: error', async () => { protocol.registerStringProtocol('electron-test', (req, cb) => { if (/redirect/.test(req.url)) return cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); await expect(net.fetch('electron-test://redirect', { redirect: 'error' })).to.eventually.be.rejectedWith('Attempted to redirect, but redirect policy was \'error\''); }); it('a 307 redirected POST request preserves the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: any; protocol.registerStringProtocol('electron-test', async (req, cb) => { if (/redirect/.test(req.url)) return cb({ statusCode: 307, headers: { location: 'electron-test://bar' } }); postedBodyData = req.uploadData![0].bytes.toString(); cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const response = await net.fetch('electron-test://redirect', { method: 'POST', body: bodyData }); expect(response.status).to.equal(200); await response.text(); expect(postedBodyData).to.equal(bodyData); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
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 './lib/window-helpers'; import { defer, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; /* 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(); }); const { port } = await listen(server); 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 = once(cookies, 'changed'); await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const [, setEventCookie, setEventCause, setEventRemoved] = await a; const b = once(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(); }); const url = (await listen(downloadServer)).url; 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(setImmediate); 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 once(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 setTimeout(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); }); const { url } = await listen(server); { const config = { pacScript: url }; 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: url }; 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); }); const { url } = await listen(server); const config = { mode: 'pac_script' as any, pacScript: url }; 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.getBlobData2()', () => { 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 content = `<html> <script> let fd = new FormData(); fd.append("data", new Blob(new Array(65_537).fill('a'))); 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 { const data = new Array(65_537).fill('a'); expect(result.toString()).to.equal(data.join('')); 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; let serverUrl: string; beforeEach(async () => { 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>'); }); serverUrl = (await listen(server)).url; }); 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(serverUrl); 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 w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(serverUrl)).to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(serverUrl); 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 w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(serverUrl), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/); await once(w.webContents, 'did-stop-loading'); await expect(w.loadURL(serverUrl + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(serverUrl + '/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 req = net.request({ url: serverUrl, session: ses1, credentials: 'include' }); req.end(); setTimeout().then(() => { 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'); } }); const { port } = await listen(server); 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 port: number; 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); }); port = (await listen(downloadServer)).port; }); 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}:${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) => { 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 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 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 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 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 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 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 = once(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 { const { url } = await listen(rangeServer); 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 = `${url}/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); // 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(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); 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 = once(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'); }); it('successfully resolves when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setPermissionRequestHandler( (_webContents, _permission, callback) => { callback(true); } ); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('successfully rejects when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setPermissionRequestHandler( (_webContents, _permission, callback) => { callback(false); } ); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); await expect(w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `)).to.eventually.be.rejectedWith('Permission denied'); }); }); 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 once(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(); }); const { url } = await listen(server); await w.loadURL(url); 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 = once(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'); }); const { port } = await listen(server); defer(() => server.close()); 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
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
shell/browser/api/electron_api_cookies.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_cookies.h" #include <utility> #include "base/time/time.h" #include "base/values.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "gin/dictionary.h" #include "gin/object_template_builder.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_inclusion_status.h" #include "net/cookies/cookie_store.h" #include "net/cookies/cookie_util.h" #include "shell/browser/cookie_change_notifier.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/gurl_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" namespace gin { template <> struct Converter<net::CookieSameSite> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CookieSameSite& val) { switch (val) { case net::CookieSameSite::UNSPECIFIED: return ConvertToV8(isolate, "unspecified"); case net::CookieSameSite::NO_RESTRICTION: return ConvertToV8(isolate, "no_restriction"); case net::CookieSameSite::LAX_MODE: return ConvertToV8(isolate, "lax"); case net::CookieSameSite::STRICT_MODE: return ConvertToV8(isolate, "strict"); } DCHECK(false); return ConvertToV8(isolate, "unknown"); } }; template <> struct Converter<net::CanonicalCookie> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CanonicalCookie& val) { gin::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("name", val.Name()); dict.Set("value", val.Value()); dict.Set("domain", val.Domain()); dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain())); dict.Set("path", val.Path()); dict.Set("secure", val.IsSecure()); dict.Set("httpOnly", val.IsHttpOnly()); dict.Set("session", !val.IsPersistent()); if (val.IsPersistent()) dict.Set("expirationDate", val.ExpiryDate().ToDoubleT()); dict.Set("sameSite", val.SameSite()); return ConvertToV8(isolate, dict).As<v8::Object>(); } }; template <> struct Converter<net::CookieChangeCause> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, const net::CookieChangeCause& val) { switch (val) { case net::CookieChangeCause::INSERTED: case net::CookieChangeCause::EXPLICIT: return gin::StringToV8(isolate, "explicit"); case net::CookieChangeCause::OVERWRITE: return gin::StringToV8(isolate, "overwrite"); case net::CookieChangeCause::EXPIRED: return gin::StringToV8(isolate, "expired"); case net::CookieChangeCause::EVICTED: return gin::StringToV8(isolate, "evicted"); case net::CookieChangeCause::EXPIRED_OVERWRITE: return gin::StringToV8(isolate, "expired-overwrite"); default: return gin::StringToV8(isolate, "unknown"); } } }; } // namespace gin namespace electron::api { namespace { // Returns whether |domain| matches |filter|. bool MatchesDomain(std::string filter, const std::string& domain) { // Add a leading '.' character to the filter domain if it doesn't exist. if (net::cookie_util::DomainIsHostOnly(filter)) filter.insert(0, "."); std::string sub_domain(domain); // Strip any leading '.' character from the input cookie domain. if (!net::cookie_util::DomainIsHostOnly(sub_domain)) sub_domain = sub_domain.substr(1); // Now check whether the domain argument is a subdomain of the filter domain. for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { if (sub_domain == filter) return true; const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. sub_domain.erase(0, next_dot); } return false; } // Returns whether |cookie| matches |filter|. bool MatchesCookie(const base::Value::Dict& filter, const net::CanonicalCookie& cookie) { const std::string* str; if ((str = filter.FindString("name")) && *str != cookie.Name()) return false; if ((str = filter.FindString("path")) && *str != cookie.Path()) return false; if ((str = filter.FindString("domain")) && !MatchesDomain(*str, cookie.Domain())) return false; absl::optional<bool> secure_filter = filter.FindBool("secure"); if (secure_filter && *secure_filter != cookie.IsSecure()) return false; absl::optional<bool> session_filter = filter.FindBool("session"); if (session_filter && *session_filter == cookie.IsPersistent()) return false; absl::optional<bool> httpOnly_filter = filter.FindBool("httpOnly"); if (httpOnly_filter && *httpOnly_filter != cookie.IsHttpOnly()) return false; return true; } // Remove cookies from |list| not matching |filter|, and pass it to |callback|. void FilterCookies(base::Value::Dict filter, gin_helper::Promise<net::CookieList> promise, const net::CookieList& cookies) { net::CookieList result; for (const auto& cookie : cookies) { if (MatchesCookie(filter, cookie)) result.push_back(cookie); } promise.Resolve(result); } void FilterCookieWithStatuses( base::Value::Dict filter, gin_helper::Promise<net::CookieList> promise, const net::CookieAccessResultList& list, const net::CookieAccessResultList& excluded_list) { FilterCookies(std::move(filter), std::move(promise), net::cookie_util::StripAccessResults(list)); } // Parse dictionary property to CanonicalCookie time correctly. base::Time ParseTimeProperty(const absl::optional<double>& value) { if (!value) // empty time means ignoring the parameter return base::Time(); if (*value == 0) // FromDoubleT would convert 0 to empty Time return base::Time::UnixEpoch(); return base::Time::FromDoubleT(*value); } std::string InclusionStatusToString(net::CookieInclusionStatus status) { if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY)) return "Failed to create httponly cookie"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_SECURE_ONLY)) return "Cannot create a secure cookie from an insecure URL"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE)) return "Failed to parse cookie"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN)) return "Failed to get cookie domain"; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX)) return "Failed because the cookie violated prefix rules."; if (status.HasExclusionReason( net::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME)) return "Cannot set cookie for current scheme"; return "Setting cookie failed"; } std::string StringToCookieSameSite(const std::string* str_ptr, net::CookieSameSite* same_site) { if (!str_ptr) { *same_site = net::CookieSameSite::LAX_MODE; return ""; } const std::string& str = *str_ptr; if (str == "unspecified") { *same_site = net::CookieSameSite::UNSPECIFIED; } else if (str == "no_restriction") { *same_site = net::CookieSameSite::NO_RESTRICTION; } else if (str == "lax") { *same_site = net::CookieSameSite::LAX_MODE; } else if (str == "strict") { *same_site = net::CookieSameSite::STRICT_MODE; } else { return "Failed to convert '" + str + "' to an appropriate cookie same site value"; } return ""; } } // namespace gin::WrapperInfo Cookies::kWrapperInfo = {gin::kEmbedderNativeGin}; Cookies::Cookies(v8::Isolate* isolate, ElectronBrowserContext* browser_context) : browser_context_(browser_context) { cookie_change_subscription_ = browser_context_->cookie_change_notifier()->RegisterCookieChangeCallback( base::BindRepeating(&Cookies::OnCookieChanged, base::Unretained(this))); } Cookies::~Cookies() = default; v8::Local<v8::Promise> Cookies::Get(v8::Isolate* isolate, const gin_helper::Dictionary& filter) { gin_helper::Promise<net::CookieList> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); base::Value::Dict dict; gin::ConvertFromV8(isolate, filter.GetHandle(), &dict); std::string url; filter.Get("url", &url); if (url.empty()) { manager->GetAllCookies( base::BindOnce(&FilterCookies, std::move(dict), std::move(promise))); } else { net::CookieOptions options; options.set_include_httponly(); options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::MakeInclusive()); options.set_do_not_update_access_time(); manager->GetCookieList(GURL(url), options, net::CookiePartitionKeyCollection::Todo(), base::BindOnce(&FilterCookieWithStatuses, std::move(dict), std::move(promise))); } return handle; } v8::Local<v8::Promise> Cookies::Remove(v8::Isolate* isolate, const GURL& url, const std::string& name) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto cookie_deletion_filter = network::mojom::CookieDeletionFilter::New(); cookie_deletion_filter->url = url; cookie_deletion_filter->cookie_name = name; auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->DeleteCookies( std::move(cookie_deletion_filter), base::BindOnce( [](gin_helper::Promise<void> promise, uint32_t num_deleted) { gin_helper::Promise<void>::ResolvePromise(std::move(promise)); }, std::move(promise))); return handle; } v8::Local<v8::Promise> Cookies::Set(v8::Isolate* isolate, base::Value::Dict details) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); const std::string* url_string = details.FindString("url"); if (!url_string) { promise.RejectWithErrorMessage("Missing required option 'url'"); return handle; } const std::string* name = details.FindString("name"); const std::string* value = details.FindString("value"); const std::string* domain = details.FindString("domain"); const std::string* path = details.FindString("path"); bool http_only = details.FindBool("httpOnly").value_or(false); const std::string* same_site_string = details.FindString("sameSite"); net::CookieSameSite same_site; std::string error = StringToCookieSameSite(same_site_string, &same_site); if (!error.empty()) { promise.RejectWithErrorMessage(error); return handle; } bool secure = details.FindBool("secure").value_or( same_site == net::CookieSameSite::NO_RESTRICTION); bool same_party = details.FindBool("sameParty") .value_or(secure && same_site != net::CookieSameSite::STRICT_MODE); GURL url(url_string ? *url_string : ""); if (!url.is_valid()) { promise.RejectWithErrorMessage( InclusionStatusToString(net::CookieInclusionStatus( net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN))); return handle; } auto canonical_cookie = net::CanonicalCookie::CreateSanitizedCookie( url, name ? *name : "", value ? *value : "", domain ? *domain : "", path ? *path : "", ParseTimeProperty(details.FindDouble("creationDate")), ParseTimeProperty(details.FindDouble("expirationDate")), ParseTimeProperty(details.FindDouble("lastAccessDate")), secure, http_only, same_site, net::COOKIE_PRIORITY_DEFAULT, same_party, absl::nullopt); if (!canonical_cookie || !canonical_cookie->IsCanonical()) { promise.RejectWithErrorMessage( InclusionStatusToString(net::CookieInclusionStatus( net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE))); return handle; } net::CookieOptions options; if (http_only) { options.set_include_httponly(); } options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::MakeInclusive()); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->SetCanonicalCookie( *canonical_cookie, url, options, base::BindOnce( [](gin_helper::Promise<void> promise, net::CookieAccessResult r) { if (r.status.IsInclude()) { promise.Resolve(); } else { promise.RejectWithErrorMessage(InclusionStatusToString(r.status)); } }, std::move(promise))); return handle; } v8::Local<v8::Promise> Cookies::FlushStore(v8::Isolate* isolate) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* storage_partition = browser_context_->GetDefaultStoragePartition(); auto* manager = storage_partition->GetCookieManagerForBrowserProcess(); manager->FlushCookieStore(base::BindOnce( gin_helper::Promise<void>::ResolvePromise, std::move(promise))); return handle; } void Cookies::OnCookieChanged(const net::CookieChangeInfo& change) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); Emit("changed", gin::ConvertToV8(isolate, change.cookie), gin::ConvertToV8(isolate, change.cause), gin::ConvertToV8(isolate, change.cause != net::CookieChangeCause::INSERTED)); } // static gin::Handle<Cookies> Cookies::Create(v8::Isolate* isolate, ElectronBrowserContext* browser_context) { return gin::CreateHandle(isolate, new Cookies(isolate, browser_context)); } gin::ObjectTemplateBuilder Cookies::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin_helper::EventEmitterMixin<Cookies>::GetObjectTemplateBuilder( isolate) .SetMethod("get", &Cookies::Get) .SetMethod("remove", &Cookies::Remove) .SetMethod("set", &Cookies::Set) .SetMethod("flushStore", &Cookies::FlushStore); } const char* Cookies::GetTypeName() { return "Cookies"; } } // namespace electron::api
closed
electron/electron
https://github.com/electron/electron
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
spec/api-net-spec.ts
import { expect } from 'chai'; import * as dns from 'dns'; import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions, protocol } from 'electron/main'; import * as http from 'http'; import * as url from 'url'; import * as path from 'path'; import { Socket } from 'net'; import { defer, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; // See https://github.com/nodejs/node/issues/40702. dns.setDefaultResultOrder('ipv4first'); const kOneKiloByte = 1024; const kOneMegaByte = kOneKiloByte * kOneKiloByte; function randomBuffer (size: number, start: number = 0, end: number = 255) { const range = 1 + end - start; const buffer = Buffer.allocUnsafe(size); for (let i = 0; i < size; ++i) { buffer[i] = start + Math.floor(Math.random() * range); } return buffer; } function randomString (length: number) { const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0)); return buffer.toString(); } async function getResponse (urlRequest: Electron.ClientRequest) { return new Promise<Electron.IncomingMessage>((resolve, reject) => { urlRequest.on('error', reject); urlRequest.on('abort', reject); urlRequest.on('response', (response) => resolve(response)); urlRequest.end(); }); } async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) { return (await collectStreamBodyBuffer(response)).toString(); } function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) { return new Promise<Buffer>((resolve, reject) => { response.on('error', reject); (response as NodeJS.EventEmitter).on('aborted', reject); const data: Buffer[] = []; response.on('data', (chunk) => data.push(chunk)); response.on('end', (chunk?: Buffer) => { if (chunk) data.push(chunk); resolve(Buffer.concat(data)); }); }); } async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> { const server = http.createServer((request, response) => { fn(request, response); // don't close if a redirect was returned if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) { n--; server.close(); } }); const sockets: Socket[] = []; server.on('connection', s => sockets.push(s)); defer(() => { server.close(); sockets.forEach(s => s.destroy()); }); return (await listen(server)).url; } function respondOnce (fn: http.RequestListener) { return respondNTimes(fn, 1); } let routeFailure = false; respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => { return respondNTimes((request, response) => { if (Object.prototype.hasOwnProperty.call(routes, request.url || '')) { (async () => { await Promise.resolve(routes[request.url || ''](request, response)); })().catch((err) => { routeFailure = true; console.error('Route handler failed, this is probably why your test failed', err); response.statusCode = 500; response.end(); }); } else { response.statusCode = 500; response.end(); expect.fail(`Unexpected URL: ${request.url}`); } }, n); }; respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1); respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => { return respondNTimes.toRoutes({ [url]: fn }, n); }; respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1); respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => { const requestUrl = '/requestUrl'; return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`); }; respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1); describe('net module', () => { beforeEach(() => { routeFailure = false; }); afterEach(async function () { await session.defaultSession.clearCache(); if (routeFailure && this.test) { if (!this.test.isFailed()) { throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error'); } } }); describe('HTTP basics', () => { it('should be able to issue a basic GET request', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('GET'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to issue a basic POST request', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('POST'); response.end(); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should fetch correct data in a GET request', async () => { const expectedBodyData = 'Hello World!'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.method).to.equal('GET'); response.end(expectedBodyData); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); const body = await collectStreamBody(response); expect(body).to.equal(expectedBodyData); }); it('should post the correct data in a POST request', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; const serverUrl = await respondOnce.toSingleURL(async (request, response) => { postedBodyData = await collectStreamBody(request); response.end(); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(postedBodyData).to.equal(bodyData); }); it('a 307 redirected POST request preserves the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; let methodAfterRedirect: string | undefined; const serverUrl = await respondNTimes.toRoutes({ '/redirect': (req, res) => { res.statusCode = 307; res.setHeader('location', serverUrl); return res.end(); }, '/': async (req, res) => { methodAfterRedirect = req.method; postedBodyData = await collectStreamBody(req); res.end(); } }, 2); const urlRequest = net.request({ method: 'POST', url: serverUrl + '/redirect' }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(methodAfterRedirect).to.equal('POST'); expect(postedBodyData).to.equal(bodyData); }); it('a 302 redirected POST request DOES NOT preserve the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: string = ''; let methodAfterRedirect: string | undefined; const serverUrl = await respondNTimes.toRoutes({ '/redirect': (req, res) => { res.statusCode = 302; res.setHeader('location', serverUrl); return res.end(); }, '/': async (req, res) => { methodAfterRedirect = req.method; postedBodyData = await collectStreamBody(req); res.end(); } }, 2); const urlRequest = net.request({ method: 'POST', url: serverUrl + '/redirect' }); urlRequest.write(bodyData); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(methodAfterRedirect).to.equal('GET'); expect(postedBodyData).to.equal(''); }); it('should support chunked encoding', async () => { let receivedRequest: http.IncomingMessage = null as any; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.chunkedEncoding = true; receivedRequest = request; request.on('data', (chunk: Buffer) => { response.write(chunk); }); request.on('end', (chunk: Buffer) => { response.end(chunk); }); }); const urlRequest = net.request({ method: 'POST', url: serverUrl }); let chunkIndex = 0; const chunkCount = 100; let sent = Buffer.alloc(0); urlRequest.chunkedEncoding = true; while (chunkIndex < chunkCount) { chunkIndex += 1; const chunk = randomBuffer(kOneKiloByte); sent = Buffer.concat([sent, chunk]); urlRequest.write(chunk); } const response = await getResponse(urlRequest); expect(receivedRequest.method).to.equal('POST'); expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked'); expect(receivedRequest.headers['content-length']).to.equal(undefined); expect(response.statusCode).to.equal(200); const received = await collectStreamBodyBuffer(response); expect(sent.equals(received)).to.be.true(); expect(chunkIndex).to.be.equal(chunkCount); }); for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) { describe(`authentication when ${JSON.stringify(extraOptions)}`, () => { it('should emit the login event when 401', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200).end('ok'); }); let loginAuthInfo: Electron.AuthInfo; const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { loginAuthInfo = authInfo; cb(user, pass); }); const response = await getResponse(request); expect(response.statusCode).to.equal(200); expect(loginAuthInfo!.realm).to.equal('Foo'); expect(loginAuthInfo!.scheme).to.equal('basic'); }); it('should receive 401 response when cancelling authentication', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }); response.end('unauthenticated'); } else { response.writeHead(200).end('ok'); } }); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { cb(); }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(401); expect(body).to.equal('unauthenticated'); }); it('should share credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondNTimes.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const bw = new BrowserWindow({ show: false }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL(serverUrl); bw.close(); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); let logInCount = 0; request.on('login', () => { logInCount++; }); const response = await getResponse(request); await collectStreamBody(response); expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached'); }); it('should share proxy credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const proxyUrl = await respondNTimes((request, response) => { if (!request.headers['proxy-authorization']) { return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`); await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' }); const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL('http://127.0.0.1:9999'); bw.close(); const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions }); let logInCount = 0; request.on('login', () => { logInCount++; }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(200); expect(body).to.equal('ok'); expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached'); }); it('should upload body when 401', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200); request.on('data', (chunk) => response.write(chunk)); request.on('end', () => response.end()); }); const requestData = randomString(kOneKiloByte); const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions }); request.on('login', (authInfo, cb) => { cb(user, pass); }); request.write(requestData); const response = await getResponse(request); const responseData = await collectStreamBody(response); expect(responseData).to.equal(requestData); }); }); } describe('authentication when {"credentials":"omit"}', () => { it('should not emit the login event when 401', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } response.writeHead(200).end('ok'); }); const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' }); request.on('login', () => { expect.fail('unexpected login event'); }); const response = await getResponse(request); expect(response.statusCode).to.equal(401); expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"'); }); it('should not share credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const serverUrl = await respondNTimes.toSingleURL((request, response) => { if (!request.headers.authorization) { return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const bw = new BrowserWindow({ show: false }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL(serverUrl); bw.close(); const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' }); request.on('login', () => { expect.fail(); }); const response = await getResponse(request); expect(response.statusCode).to.equal(401); expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"'); }); it('should share proxy credentials with WebContents', async () => { const [user, pass] = ['user', 'pass']; const proxyUrl = await respondNTimes((request, response) => { if (!request.headers['proxy-authorization']) { return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end(); } return response.writeHead(200).end('ok'); }, 2); const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`); await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' }); const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); bw.webContents.on('login', (event, details, authInfo, cb) => { event.preventDefault(); cb(user, pass); }); await bw.loadURL('http://127.0.0.1:9999'); bw.close(); const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' }); request.on('login', () => { expect.fail(); }); const response = await getResponse(request); const body = await collectStreamBody(response); expect(response.statusCode).to.equal(200); expect(body).to.equal('ok'); }); }); }); describe('ClientRequest API', () => { it('request/response objects should emit expected events', async () => { const bodyData = randomString(kOneKiloByte); const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(bodyData); }); const urlRequest = net.request(serverUrl); // request close event const closePromise = once(urlRequest, 'close'); // request finish event const finishPromise = once(urlRequest, 'close'); // request "response" event const response = await getResponse(urlRequest); response.on('error', (error: Error) => { expect(error).to.be.an('Error'); }); const statusCode = response.statusCode; expect(statusCode).to.equal(200); // response data event // respond end event const body = await collectStreamBody(response); expect(body).to.equal(bodyData); urlRequest.on('error', (error) => { expect(error).to.be.an('Error'); }); await Promise.all([closePromise, finishPromise]); }); it('should be able to set a custom HTTP request header before first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); urlRequest.write(''); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to set a non-string object as a header value', async () => { const customHeaderName = 'Some-Integer-Value'; const customHeaderValue = 900; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString()); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue as any); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); urlRequest.write(''); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not change the case of header name', async () => { const customHeaderName = 'X-Header-Name'; const customHeaderValue = 'value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString()); expect(request.rawHeaders.includes(customHeaderName)).to.equal(true); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.write(''); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not be able to set a custom HTTP request header after first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.write(''); expect(() => { urlRequest.setHeader(customHeaderName, customHeaderValue); }).to.throw(); expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to remove a custom HTTP request header before first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.removeHeader(customHeaderName); expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined); urlRequest.write(''); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should not be able to remove a custom HTTP request header after first write', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderName, customHeaderValue); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); urlRequest.write(''); expect(() => { urlRequest.removeHeader(customHeaderName); }).to.throw(); expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should keep the order of headers', async () => { const customHeaderNameA = 'X-Header-100'; const customHeaderNameB = 'X-Header-200'; const serverUrl = await respondOnce.toSingleURL((request, response) => { const headerNames = Array.from(Object.keys(request.headers)); const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase()); const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase()); expect(headerBIndex).to.be.below(headerAIndex); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.setHeader(customHeaderNameB, 'b'); urlRequest.setHeader(customHeaderNameA, 'a'); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to set cookie header line', async () => { const cookieHeaderName = 'Cookie'; const cookieHeaderValue = 'test=12345'; const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`); const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); await customSession.cookies.set({ url: `${serverUrl}`, name: 'test', value: '11111', expirationDate: 0 }); const urlRequest = net.request({ method: 'GET', url: serverUrl, session: customSession }); urlRequest.setHeader(cookieHeaderName, cookieHeaderValue); expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should be able to receive cookies', async () => { const cookie = ['cookie1', 'cookie2']; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', cookie); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.headers['set-cookie']).to.have.same.members(cookie); }); it('should be able to receive content-type', async () => { const contentType = 'mime/test; charset=test'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('content-type', contentType); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.headers['content-type']).to.equal(contentType); }); it('should not use the sessions cookie store by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', `${request.headers.cookie!}`); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const urlRequest = net.request({ url: serverUrl, session: sess }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal('undefined'); }); for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) { describe(`when ${JSON.stringify(extraOptions)}`, () => { it('should be able to use the sessions cookie store', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', request.headers.cookie!); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`); }); it('should be able to use the sessions cookie store with set-cookie', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', 'foo=bar'); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); let cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(0); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); await collectStreamBody(await getResponse(urlRequest)); cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(1); expect(cookies[0]).to.deep.equal({ name: 'foo', value: 'bar', domain: '127.0.0.1', hostOnly: true, path: '/', secure: false, httpOnly: false, session: true, sameSite: 'unspecified' }); }); ['Lax', 'Strict'].forEach((mode) => { it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => { const serverUrl = await respondNTimes.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', `same=site; SameSite=${mode}`); response.setHeader('x-cookie', `${request.headers.cookie}`); response.end(); }, 2); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); let cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(0); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response = await getResponse(urlRequest); expect(response.headers['x-cookie']).to.equal('undefined'); await collectStreamBody(response); cookies = await sess.cookies.get({}); expect(cookies).to.have.lengthOf(1); expect(cookies[0]).to.deep.equal({ name: 'same', value: 'site', domain: '127.0.0.1', hostOnly: true, path: '/', secure: false, httpOnly: false, session: true, sameSite: mode.toLowerCase() }); const urlRequest2 = net.request({ url: serverUrl, session: sess, ...extraOptions }); const response2 = await getResponse(urlRequest2); expect(response2.headers['x-cookie']).to.equal('same=site'); }); }); it('should be able to use the sessions cookie store safely across redirects', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { response.statusCode = 302; response.statusMessage = 'Moved'; const newUrl = await respondOnce.toSingleURL((req, res) => { res.statusCode = 200; res.statusMessage = 'OK'; res.setHeader('x-cookie', req.headers.cookie!); res.end(); }); response.setHeader('x-cookie', request.headers.cookie!); response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost')); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookie127Val = `${Date.now()}-127`; const cookieLocalVal = `${Date.now()}-local`; const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost'); expect(localhostUrl).to.not.equal(serverUrl); // cookies with lax or strict same-site settings will not // persist after redirects. no_restriction must be used await Promise.all([ sess.cookies.set({ url: serverUrl, name: 'wild_cookie', sameSite: 'no_restriction', value: cookie127Val }), sess.cookies.set({ url: localhostUrl, name: 'wild_cookie', sameSite: 'no_restriction', value: cookieLocalVal }) ]); const urlRequest = net.request({ url: serverUrl, session: sess, ...extraOptions }); urlRequest.on('redirect', (status, method, url, headers) => { // The initial redirect response should have received the 127 value here expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`); urlRequest.followRedirect(); }); const response = await getResponse(urlRequest); // We expect the server to have received the localhost value here // The original request was to a 127.0.0.1 URL // That request would have the cookie127Val cookie attached // The request is then redirect to a localhost URL (different site) // Because we are using the session cookie store it should do the safe / secure thing // and attach the cookies for the new target domain expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`); }); }); } it('should be able correctly filter out cookies that are secure', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1', secure: true }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', secure: false }) ]); const secureCookies = await sess.cookies.get({ secure: true }); expect(secureCookies).to.have.lengthOf(1); expect(secureCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ secure: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); it('should be able correctly filter out cookies that are session', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1' }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', expirationDate: Math.round(Date.now() / 1000) + 10000 }) ]); const sessionCookies = await sess.cookies.get({ session: true }); expect(sessionCookies).to.have.lengthOf(1); expect(sessionCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ session: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); it('should be able correctly filter out cookies that are httpOnly', async () => { const sess = session.fromPartition(`cookie-tests-${Math.random()}`); await Promise.all([ sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie1', value: '1', httpOnly: true }), sess.cookies.set({ url: 'https://electronjs.org', domain: 'electronjs.org', name: 'cookie2', value: '2', httpOnly: false }) ]); const httpOnlyCookies = await sess.cookies.get({ httpOnly: true }); expect(httpOnlyCookies).to.have.lengthOf(1); expect(httpOnlyCookies[0].name).to.equal('cookie1'); const cookies = await sess.cookies.get({ httpOnly: false }); expect(cookies).to.have.lengthOf(1); expect(cookies[0].name).to.equal('cookie2'); }); describe('when {"credentials":"omit"}', () => { it('should not send cookies'); it('should not store cookies'); }); it('should set sec-fetch-site to same-origin for request from same origin', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('same-origin'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-site to same-origin for request with the same origin header', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('same-origin'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.setHeader('Origin', serverUrl); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-site to cross-site for request from other origin', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-site']).to.equal('cross-site'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: 'https://not-exists.com' }); await collectStreamBody(await getResponse(urlRequest)); }); it('should not send sec-fetch-user header by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers).not.to.have.property('sec-fetch-user'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-user to ?1 if requested', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-user']).to.equal('?1'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.setHeader('sec-fetch-user', '?1'); await collectStreamBody(await getResponse(urlRequest)); }); it('should set sec-fetch-mode to no-cors by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-mode']).to.equal('no-cors'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); ['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => { it(`should set sec-fetch-mode to ${mode} if requested`, async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-mode']).to.equal(mode); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); urlRequest.setHeader('sec-fetch-mode', mode); await collectStreamBody(await getResponse(urlRequest)); }); }); it('should set sec-fetch-dest to empty by default', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-dest']).to.equal('empty'); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl }); await collectStreamBody(await getResponse(urlRequest)); }); [ 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font', 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet', 'report', 'script', 'serviceworker', 'style', 'track', 'video', 'worker', 'xslt' ].forEach((dest) => { it(`should set sec-fetch-dest to ${dest} if requested`, async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers['sec-fetch-dest']).to.equal(dest); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request({ url: serverUrl, origin: serverUrl }); urlRequest.setHeader('sec-fetch-dest', dest); await collectStreamBody(await getResponse(urlRequest)); }); }); it('should be able to abort an HTTP request before first write', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); expect.fail('Unexpected request event'); }); const urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('unexpected response event'); }); const aborted = once(urlRequest, 'abort'); urlRequest.abort(); urlRequest.write(''); urlRequest.end(); await aborted; }); it('it should be able to abort an HTTP request before request end', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL(() => { requestReceivedByServer = true; urlRequest!.abort(); }); let requestAbortEventEmitted = false; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { expect.fail('Unexpected finish event'); }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.on('abort', () => { requestAbortEventEmitted = true; }); const p = once(urlRequest, 'close'); urlRequest.chunkedEncoding = true; urlRequest.write(randomString(kOneKiloByte)); await p; expect(requestReceivedByServer).to.equal(true); expect(requestAbortEventEmitted).to.equal(true); }); it('it should be able to abort an HTTP request after request end and before response', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL((request, response) => { requestReceivedByServer = true; urlRequest!.abort(); process.nextTick(() => { response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); }); let requestFinishEventEmitted = false; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.equal(true); expect(requestReceivedByServer).to.equal(true); }); it('it should be able to abort an HTTP request after response start', async () => { let requestReceivedByServer = false; const serverUrl = await respondOnce.toSingleURL((request, response) => { requestReceivedByServer = true; response.statusCode = 200; response.statusMessage = 'OK'; response.write(randomString(kOneKiloByte)); }); let requestFinishEventEmitted = false; let requestResponseEventEmitted = false; let responseCloseEventEmitted = false; const urlRequest = net.request(serverUrl); urlRequest.on('response', (response) => { requestResponseEventEmitted = true; const statusCode = response.statusCode; expect(statusCode).to.equal(200); response.on('data', () => {}); response.on('end', () => { expect.fail('Unexpected end event'); }); response.on('error', () => { expect.fail('Unexpected error event'); }); response.on('close' as any, () => { responseCloseEventEmitted = true; }); urlRequest.abort(); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event'); expect(requestReceivedByServer).to.be.true('request should be received by the server'); expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted'); expect(responseCloseEventEmitted).to.be.true('response should emit "close" event'); }); it('abort event should be emitted at most once', async () => { let requestReceivedByServer = false; let urlRequest: ClientRequest | null = null; const serverUrl = await respondOnce.toSingleURL(() => { requestReceivedByServer = true; urlRequest!.abort(); urlRequest!.abort(); }); let requestFinishEventEmitted = false; let abortsEmitted = 0; urlRequest = net.request(serverUrl); urlRequest.on('response', () => { expect.fail('Unexpected response event'); }); urlRequest.on('finish', () => { requestFinishEventEmitted = true; }); urlRequest.on('error', () => { expect.fail('Unexpected error event'); }); urlRequest.on('abort', () => { abortsEmitted++; }); urlRequest.end(randomString(kOneKiloByte)); await once(urlRequest, 'abort'); expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event'); expect(requestReceivedByServer).to.be.true('request should be received by server'); expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event'); }); it('should allow to read response body from non-2xx response', async () => { const bodyData = randomString(kOneKiloByte); const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 404; response.end(bodyData); }); const urlRequest = net.request(serverUrl); const bodyCheckPromise = getResponse(urlRequest).then(r => { expect(r.statusCode).to.equal(404); return r; }).then(collectStreamBody).then(receivedBodyData => { expect(receivedBodyData.toString()).to.equal(bodyData); }); const eventHandlers = Promise.all([ bodyCheckPromise, once(urlRequest, 'close') ]); urlRequest.end(); await eventHandlers; }); describe('webRequest', () => { afterEach(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); it('Should throw when invalid filters are passed', () => { expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.'); expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.'); }); it('Should not throw when valid filters are passed', () => { expect(() => { session.defaultSession.webRequest.onBeforeRequest( { urls: ['*://www.googleapis.com/'] }, (details, callback) => { callback({ cancel: false }); } ); }).to.not.throw(); }); it('Requests should be intercepted by webRequest module', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); let requestIsIntercepted = false; session.defaultSession.webRequest.onBeforeRequest( (details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request(`${serverUrl}${requestUrl}`); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); it('should to able to create and intercept a request using a custom session object', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; const customPartitionName = `custom-partition-${Math.random()}`; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); session.defaultSession.webRequest.onBeforeRequest(() => { expect.fail('Request should not be intercepted by the default session'); }); const customSession = session.fromPartition(customPartitionName, { cache: false }); let requestIsIntercepted = false; customSession.webRequest.onBeforeRequest((details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}`, session: customSession }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); it('should to able to create and intercept a request using a custom partition name', async () => { const requestUrl = '/requestUrl'; const redirectUrl = '/redirectUrl'; const customPartitionName = `custom-partition-${Math.random()}`; let requestIsRedirected = false; const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => { requestIsRedirected = true; response.end(); }); session.defaultSession.webRequest.onBeforeRequest(() => { expect.fail('Request should not be intercepted by the default session'); }); const customSession = session.fromPartition(customPartitionName, { cache: false }); let requestIsIntercepted = false; customSession.webRequest.onBeforeRequest((details, callback) => { if (details.url === `${serverUrl}${requestUrl}`) { requestIsIntercepted = true; // Disabled due to false positive in StandardJS // eslint-disable-next-line standard/no-callback-literal callback({ redirectURL: `${serverUrl}${redirectUrl}` }); } else { callback({ cancel: false }); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}`, partition: customPartitionName }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL'); expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module'); }); }); it('should throw when calling getHeader without a name', () => { expect(() => { (net.request({ url: 'https://test' }).getHeader as any)(); }).to.throw(/`name` is required for getHeader\(name\)/); expect(() => { net.request({ url: 'https://test' }).getHeader(null as any); }).to.throw(/`name` is required for getHeader\(name\)/); }); it('should throw when calling removeHeader without a name', () => { expect(() => { (net.request({ url: 'https://test' }).removeHeader as any)(); }).to.throw(/`name` is required for removeHeader\(name\)/); expect(() => { net.request({ url: 'https://test' }).removeHeader(null as any); }).to.throw(/`name` is required for removeHeader\(name\)/); }); it('should follow redirect when no redirect handler is provided', async () => { const requestUrl = '/302'; const serverUrl = await respondOnce.toRoutes({ '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}${requestUrl}` }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); }); it('should follow redirect chain when no redirect handler is provided', async () => { const serverUrl = await respondOnce.toRoutes({ '/redirectChain': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/302'); response.end(); }, '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}/redirectChain` }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); }); it('should not follow redirect when request is canceled in redirect handler', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }); const urlRequest = net.request({ url: serverUrl }); urlRequest.end(); urlRequest.on('redirect', () => { urlRequest.abort(); }); urlRequest.on('error', () => {}); urlRequest.on('response', () => { expect.fail('Unexpected response'); }); await once(urlRequest, 'abort'); }); it('should not follow redirect when mode is error', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }); const urlRequest = net.request({ url: serverUrl, redirect: 'error' }); urlRequest.end(); await once(urlRequest, 'error'); }); it('should follow redirect when handler calls callback', async () => { const serverUrl = await respondOnce.toRoutes({ '/redirectChain': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/302'); response.end(); }, '/302': (request, response) => { response.statusCode = 302; response.setHeader('Location', '/200'); response.end(); }, '/200': (request, response) => { response.statusCode = 200; response.end(); } }); const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' }); const redirects: string[] = []; urlRequest.on('redirect', (status, method, url) => { redirects.push(url); urlRequest.followRedirect(); }); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(redirects).to.deep.equal([ `${serverUrl}/302`, `${serverUrl}/200` ]); }); it('should throw if given an invalid session option', () => { expect(() => { net.request({ url: 'https://foo', session: 1 as any }); }).to.throw('`session` should be an instance of the Session class'); }); it('should throw if given an invalid partition option', () => { expect(() => { net.request({ url: 'https://foo', partition: 1 as any }); }).to.throw('`partition` should be a string'); }); it('should be able to create a request with options', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => { expect(request.method).to.equal('GET'); expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const serverUrl = url.parse(serverUrlUnparsed); const options = { port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined, hostname: '127.0.0.1', headers: { [customHeaderName]: customHeaderValue } }; const urlRequest = net.request(options); const response = await getResponse(urlRequest); expect(response.statusCode).to.be.equal(200); await collectStreamBody(response); }); it('should be able to pipe a readable stream into a net request', async () => { const bodyData = randomString(kOneMegaByte); let netRequestReceived = false; let netRequestEnded = false; const [nodeServerUrl, netServerUrl] = await Promise.all([ respondOnce.toSingleURL((request, response) => response.end(bodyData)), respondOnce.toSingleURL((request, response) => { netRequestReceived = true; let receivedBodyData = ''; request.on('data', (chunk) => { receivedBodyData += chunk.toString(); }); request.on('end', (chunk: Buffer | undefined) => { netRequestEnded = true; if (chunk) { receivedBodyData += chunk.toString(); } expect(receivedBodyData).to.be.equal(bodyData); response.end(); }); }) ]); const nodeRequest = http.request(nodeServerUrl); const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse; const netRequest = net.request(netServerUrl); const responsePromise = once(netRequest, 'response'); // TODO(@MarshallOfSound) - FIXME with #22730 nodeResponse.pipe(netRequest as any); const [netResponse] = await responsePromise; expect(netResponse.statusCode).to.equal(200); await collectStreamBody(netResponse); expect(netRequestReceived).to.be.true('net request received'); expect(netRequestEnded).to.be.true('net request ended'); }); it('should report upload progress', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const netRequest = net.request({ url: serverUrl, method: 'POST' }); expect(netRequest.getUploadProgress()).to.have.property('active', false); netRequest.end(Buffer.from('hello')); const [position, total] = await once(netRequest, 'upload-progress'); expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total }); }); it('should emit error event on server socket destroy', async () => { const serverUrl = await respondOnce.toSingleURL((request) => { request.socket.destroy(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); const [error] = await once(urlRequest, 'error'); expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE'); }); it('should emit error event on server request destroy', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.destroy(); response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(randomBuffer(kOneMegaByte)); const [error] = await once(urlRequest, 'error'); expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']); }); it('should not emit any event after close', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); await once(urlRequest, 'close'); await new Promise((resolve, reject) => { ['finish', 'abort', 'close', 'error'].forEach(evName => { urlRequest.on(evName as any, () => { reject(new Error(`Unexpected ${evName} event`)); }); }); setTimeout(50).then(resolve); }); }); it('should remove the referer header when no referrer url specified', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers.referer).to.equal(undefined); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.end(); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); it('should set the referer header when a referrer url specified', async () => { const referrerURL = 'https://www.electronjs.org/'; const serverUrl = await respondOnce.toSingleURL((request, response) => { expect(request.headers.referer).to.equal(referrerURL); response.statusCode = 200; response.statusMessage = 'OK'; response.end(); }); // The referrerPolicy must be unsafe-url because the referrer's origin // doesn't match the loaded page. With the default referrer policy // (strict-origin-when-cross-origin), the request will be canceled by the // network service when the referrer header is invalid. // See: // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41 // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698 // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' }); urlRequest.setHeader('referer', referrerURL); urlRequest.end(); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); await collectStreamBody(response); }); }); describe('IncomingMessage API', () => { it('response object should implement the IncomingMessage API', async () => { const customHeaderName = 'Some-Custom-Header-Name'; const customHeaderValue = 'Some-Customer-Header-Value'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader(customHeaderName, customHeaderValue); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); const headerValue = headers[customHeaderName.toLowerCase()]; expect(headerValue).to.equal(customHeaderValue); const rawHeaders = response.rawHeaders; expect(rawHeaders).to.be.an('array'); expect(rawHeaders[0]).to.equal(customHeaderName); expect(rawHeaders[1]).to.equal(customHeaderValue); const httpVersion = response.httpVersion; expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1); const httpVersionMajor = response.httpVersionMajor; expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1); const httpVersionMinor = response.httpVersionMinor; expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0); await collectStreamBody(response); }); it('should discard duplicate headers', async () => { const includedHeader = 'max-forwards'; const discardableHeader = 'Max-Forwards'; const includedHeaderValue = 'max-fwds-val'; const discardableHeaderValue = 'max-fwds-val-two'; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader(discardableHeader, discardableHeaderValue); response.setHeader(includedHeader, includedHeaderValue); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property(includedHeader); expect(headers).to.not.have.property(discardableHeader); expect(headers[includedHeader]).to.equal(includedHeaderValue); await collectStreamBody(response); }); it('should join repeated non-discardable header values with ,', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('referrer-policy', ['first-text', 'second-text']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('referrer-policy'); expect(headers['referrer-policy']).to.equal('first-text, second-text'); await collectStreamBody(response); }); it('should not join repeated discardable header values with ,', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('last-modified', ['yesterday', 'today']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('last-modified'); expect(headers['last-modified']).to.equal('yesterday'); await collectStreamBody(response); }); it('should make set-cookie header an array even if single value', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', 'chocolate-chip'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('set-cookie'); expect(headers['set-cookie']).to.be.an('array'); expect(headers['set-cookie'][0]).to.equal('chocolate-chip'); await collectStreamBody(response); }); it('should keep set-cookie header an array when an array', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('set-cookie'); expect(headers['set-cookie']).to.be.an('array'); expect(headers['set-cookie'][0]).to.equal('chocolate-chip'); expect(headers['set-cookie'][1]).to.equal('oatmeal'); await collectStreamBody(response); }); it('should lowercase header keys', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('HEADER-KEY', ['header-value']); response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']); response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']); response.setHeader('LAST-modified', 'yesterday'); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const headers = response.headers; expect(headers).to.be.an('object'); expect(headers).to.have.property('header-key'); expect(headers).to.have.property('set-cookie'); expect(headers).to.have.property('referrer-policy'); expect(headers).to.have.property('last-modified'); await collectStreamBody(response); }); it('should return correct raw headers', async () => { const customHeaders: [string, string|string[]][] = [ ['HEADER-KEY-ONE', 'header-value-one'], ['set-cookie', 'chocolate-chip'], ['header-key-two', 'header-value-two'], ['referrer-policy', ['first-text', 'second-text']], ['HEADER-KEY-THREE', 'header-value-three'], ['last-modified', ['first-text', 'second-text']], ['header-key-four', 'header-value-four'] ]; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; customHeaders.forEach((headerTuple) => { response.setHeader(headerTuple[0], headerTuple[1]); }); response.end(); }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); expect(response.statusCode).to.equal(200); expect(response.statusMessage).to.equal('OK'); const rawHeaders = response.rawHeaders; expect(rawHeaders).to.be.an('array'); let rawHeadersIdx = 0; customHeaders.forEach((headerTuple) => { const headerKey = headerTuple[0]; const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]]; headerValues.forEach((headerValue) => { expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey); expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue); rawHeadersIdx += 2; }); }); await collectStreamBody(response); }); it('should be able to pipe a net response into a writable stream', async () => { const bodyData = randomString(kOneKiloByte); let nodeRequestProcessed = false; const [netServerUrl, nodeServerUrl] = await Promise.all([ respondOnce.toSingleURL((request, response) => response.end(bodyData)), respondOnce.toSingleURL(async (request, response) => { const receivedBodyData = await collectStreamBody(request); expect(receivedBodyData).to.be.equal(bodyData); nodeRequestProcessed = true; response.end(); }) ]); const netRequest = net.request(netServerUrl); const netResponse = await getResponse(netRequest); const serverUrl = url.parse(nodeServerUrl); const nodeOptions = { method: 'POST', path: serverUrl.path, port: serverUrl.port }; const nodeRequest = http.request(nodeOptions); const nodeResponsePromise = once(nodeRequest, 'response'); // TODO(@MarshallOfSound) - FIXME with #22730 (netResponse as any).pipe(nodeRequest); const [nodeResponse] = await nodeResponsePromise; netRequest.end(); await collectStreamBody(nodeResponse); expect(nodeRequestProcessed).to.equal(true); }); it('should correctly throttle an incoming stream', async () => { let numChunksSent = 0; const serverUrl = await respondOnce.toSingleURL((request, response) => { const data = randomString(kOneMegaByte); const write = () => { let ok = true; do { numChunksSent++; if (numChunksSent > 30) return; ok = response.write(data); } while (ok); response.once('drain', write); }; write(); }); const urlRequest = net.request(serverUrl); urlRequest.on('response', () => {}); urlRequest.end(); await setTimeout(2000); // TODO(nornagon): I think this ought to max out at 20, but in practice // it seems to exceed that sometimes. This is at 25 to avoid test flakes, // but we should investigate if there's actually something broken here and // if so fix it and reset this to max at 20, and if not then delete this // comment. expect(numChunksSent).to.be.at.most(25); }); }); describe('net.isOnline', () => { it('getter returns boolean', () => { expect(net.isOnline()).to.be.a('boolean'); }); it('property returns boolean', () => { expect(net.online).to.be.a('boolean'); }); }); describe('Stability and performance', () => { it('should free unreferenced, never-started request objects without crash', (done) => { net.request('https://test'); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); done(); }); }); it('should collect on-going requests without crash', async () => { let finishResponse: (() => void) | null = null; const serverUrl = await respondOnce.toSingleURL((request, response) => { response.write(randomString(kOneKiloByte)); finishResponse = () => { response.write(randomString(kOneKiloByte)); response.end(); }; }); const urlRequest = net.request(serverUrl); const response = await getResponse(urlRequest); process.nextTick(() => { // Trigger a garbage collection. const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); finishResponse!(); }); await collectStreamBody(response); }); it('should collect unreferenced, ended requests without crash', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end(); }); const urlRequest = net.request(serverUrl); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); const response = await getResponse(urlRequest); await collectStreamBody(response); }); it('should finish sending data when urlRequest is unreferenced', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); expect(received.length).to.equal(kOneMegaByte); response.end(); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.write(randomBuffer(kOneMegaByte)); const response = await getResponse(urlRequest); await collectStreamBody(response); }); it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); const response = await getResponse(urlRequest); await collectStreamBody(response); process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); await collectStreamBody(await getResponse(urlRequest)); }); it('should finish sending data when urlRequest is unreferenced', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.write(randomBuffer(kOneMegaByte)); await collectStreamBody(await getResponse(urlRequest)); }); it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => { const serverUrl = await respondOnce.toSingleURL(async (request, response) => { const received = await collectStreamBodyBuffer(request); response.end(); expect(received.length).to.equal(kOneMegaByte); }); const urlRequest = net.request(serverUrl); urlRequest.on('close', () => { process.nextTick(() => { const v8Util = process._linkedBinding('electron_common_v8_util'); v8Util.requestGarbageCollectionForTesting(); }); }); urlRequest.chunkedEncoding = true; urlRequest.write(randomBuffer(kOneMegaByte)); await collectStreamBody(await getResponse(urlRequest)); }); }); describe('non-http schemes', () => { it('should be rejected by net.request', async () => { expect(() => { net.request('file://bar'); }).to.throw('ClientRequest only supports http: and https: protocols'); }); it('should be rejected by net.request when passed in url:', async () => { expect(() => { net.request({ url: 'file://bar' }); }).to.throw('ClientRequest only supports http: and https: protocols'); }); }); describe('net.fetch', () => { // NB. there exist much more comprehensive tests for fetch() in the form of // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch // It's possible to run these tests against net.fetch(), but the test // harness to do so is quite complex and hasn't been munged to smoothly run // inside the Electron test runner yet. // // In the meantime, here are some tests for basic functionality and // Electron-specific behavior. describe('basic', () => { it('can fetch http urls', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.end('test'); }); const resp = await net.fetch(serverUrl); expect(resp.ok).to.be.true(); expect(await resp.text()).to.equal('test'); }); it('can upload a string body', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.on('data', chunk => response.write(chunk)); request.on('end', () => response.end()); }); const resp = await net.fetch(serverUrl, { method: 'POST', body: 'anchovies' }); expect(await resp.text()).to.equal('anchovies'); }); it('can read response as an array buffer', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { request.on('data', chunk => response.write(chunk)); request.on('end', () => response.end()); }); const resp = await net.fetch(serverUrl, { method: 'POST', body: 'anchovies' }); expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies'); }); it('can read response as form data', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.setHeader('content-type', 'application/x-www-form-urlencoded'); response.end('foo=bar'); }); const resp = await net.fetch(serverUrl); const result = await resp.formData(); expect(result.get('foo')).to.equal('bar'); }); it('should be able to use a session cookie store', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; response.setHeader('x-cookie', request.headers.cookie!); response.end(); }); const sess = session.fromPartition(`cookie-tests-${Math.random()}`); const cookieVal = `${Date.now()}`; await sess.cookies.set({ url: serverUrl, name: 'wild_cookie', value: cookieVal }); const response = await sess.fetch(serverUrl, { credentials: 'include' }); expect(response.headers.get('x-cookie')).to.equal(`wild_cookie=${cookieVal}`); }); it('should reject promise on DNS failure', async () => { const r = net.fetch('https://i.do.not.exist'); await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/); }); it('should reject body promise when stream fails', async () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.write('first chunk'); setTimeout().then(() => response.destroy()); }); const r = await net.fetch(serverUrl); expect(r.status).to.equal(200); await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/); }); }); it('can request file:// URLs', async () => { const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()); expect(resp.ok).to.be.true(); // trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA expect((await resp.text()).trimRight()).to.equal('hello world'); }); it('can make requests to custom protocols', async () => { protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const body = await net.fetch('electron-test://foo').then(r => r.text()); expect(body).to.equal('hello electron-test://foo'); }); it('runs through intercept handlers', async () => { protocol.interceptStringProtocol('http', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.uninterceptProtocol('http'); }); const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('hello http://foo/'); }); it('file: runs through intercept handlers', async () => { protocol.interceptStringProtocol('file', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.uninterceptProtocol('file'); }); const body = await net.fetch('file://foo').then(r => r.text()); expect(body).to.equal('hello file://foo/'); }); it('can be redirected', async () => { protocol.interceptStringProtocol('file', (req, cb) => { cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); }); defer(() => { protocol.uninterceptProtocol('file'); }); protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const body = await net.fetch('file://foo').then(r => r.text()); expect(body).to.equal('hello electron-test://bar'); }); it('should not follow redirect when redirect: error', async () => { protocol.registerStringProtocol('electron-test', (req, cb) => { if (/redirect/.test(req.url)) return cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); await expect(net.fetch('electron-test://redirect', { redirect: 'error' })).to.eventually.be.rejectedWith('Attempted to redirect, but redirect policy was \'error\''); }); it('a 307 redirected POST request preserves the body', async () => { const bodyData = 'Hello World!'; let postedBodyData: any; protocol.registerStringProtocol('electron-test', async (req, cb) => { if (/redirect/.test(req.url)) return cb({ statusCode: 307, headers: { location: 'electron-test://bar' } }); postedBodyData = req.uploadData![0].bytes.toString(); cb('hello ' + req.url); }); defer(() => { protocol.unregisterProtocol('electron-test'); }); const response = await net.fetch('electron-test://redirect', { method: 'POST', body: bodyData }); expect(response.status).to.equal(200); await response.text(); expect(postedBodyData).to.equal(bodyData); }); }); });
closed
electron/electron
https://github.com/electron/electron
37,568
[Bug]: Cookie is not set from parition when domain is present
### 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 23.0.0 ### What operating system are you using? macOS ### Operating System Version macOS Venture 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The following code when a valid session cookie is set in the rederer throws the following error. I am able to set a cookie when no domain is present. ``` (node:52646) UnhandledPromiseRejectionWarning: Error: Failed to parse cookie ``` ```typescript const createWindow = async (): Promise<void> => { console.log(); const partitionSession = session.fromPartition("persist:federated"); const sessionCookie = store.get("__session"); if (sessionCookie) { await partitionSession.cookies.set(sessionCookie); } // Create the browser window. mainWindow = new BrowserWindow({ height: 600, width: 800, webPreferences: { preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY, /** * The next two items are not normally set and required * because of our nodejs usage */ nodeIntegration: true, contextIsolation: false, partition: "persist:federated", session: partitionSession, }, }); // and load the index.html of the app. mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY); // Open the DevTools. mainWindow.webContents.openDevTools(); const cookies = mainWindow.webContents.session.cookies; cookies.on("changed", (event, cookie, cause, removed) => { if (cookie.name === "__session") store.set("__session", { url: "http://localhost:3000", name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, }); }); }; ``` ### Actual Behavior A cookie should be set when the domain option is present. ### Testcase Gist URL https://gist.github.com/8ee681e77bbcf7603642532fc27b0334 ### Additional Information _No response_
https://github.com/electron/electron/issues/37568
https://github.com/electron/electron/pull/37586
48d0b09ad932aabc91ef072c862f3489202e40fd
b8f970c1c710c7e43cff6770fa845b96445cdaf8
2023-03-13T17:16:17Z
c++
2023-03-16T12:48:14Z
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 './lib/window-helpers'; import { defer, listen } from './lib/spec-helpers'; import { once } from 'events'; import { setTimeout } from 'timers/promises'; /* 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(); }); const { port } = await listen(server); 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 = once(cookies, 'changed'); await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 }); const [, setEventCookie, setEventCause, setEventRemoved] = await a; const b = once(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(); }); const url = (await listen(downloadServer)).url; 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(setImmediate); 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 once(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 setTimeout(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); }); const { url } = await listen(server); { const config = { pacScript: url }; 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: url }; 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); }); const { url } = await listen(server); const config = { mode: 'pac_script' as any, pacScript: url }; 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.getBlobData2()', () => { 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 content = `<html> <script> let fd = new FormData(); fd.append("data", new Blob(new Array(65_537).fill('a'))); 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 { const data = new Array(65_537).fill('a'); expect(result.toString()).to.equal(data.join('')); 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; let serverUrl: string; beforeEach(async () => { 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>'); }); serverUrl = (await listen(server)).url; }); 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(serverUrl); 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 w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(serverUrl)).to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(serverUrl); 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 w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await expect(w.loadURL(serverUrl), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/); await once(w.webContents, 'did-stop-loading'); await expect(w.loadURL(serverUrl + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/); expect(w.webContents.getTitle()).to.equal(serverUrl + '/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 req = net.request({ url: serverUrl, session: ses1, credentials: 'include' }); req.end(); setTimeout().then(() => { 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'); } }); const { port } = await listen(server); 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 port: number; 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); }); port = (await listen(downloadServer)).port; }); 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}:${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) => { 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 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 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 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 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 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 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 = once(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 { const { url } = await listen(rangeServer); 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 = `${url}/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); // 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(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); 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 = once(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'); }); it('successfully resolves when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setPermissionRequestHandler( (_webContents, _permission, callback) => { callback(true); } ); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const { ok, message } = await w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `); expect(ok).to.be.true(message); }); it('successfully rejects when calling legacy getUserMedia', async () => { const ses = session.fromPartition('' + Math.random()); ses.setPermissionRequestHandler( (_webContents, _permission, callback) => { callback(false); } ); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); await expect(w.webContents.executeJavaScript(` new Promise((resolve, reject) => navigator.getUserMedia({ video: true, audio: true, }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) `)).to.eventually.be.rejectedWith('Permission denied'); }); }); 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 once(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(); }); const { url } = await listen(server); await w.loadURL(url); 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 = once(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'); }); const { port } = await listen(server); defer(() => server.close()); 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
37,487
[Bug]: Restoring dock icon after creating multiple overlay windows creates duplicates
### 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 23.1.1, 24.0.0-alpha.7, 25.0.0-nightly.20230302 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Creating several windows with `visibleOnFullScreen: true` and calling `app.dock.show()` should only show one icon in the dock. ### Actual Behavior Creating several windows with `visibleOnFullScreen: true` and calling `app.dock.show()` has a timing issue: it allows multiple dock icons to appear and detach, surviving even after you close the application. <img width="552" alt="screenshot: duplicate dock icons" src="https://user-images.githubusercontent.com/10053423/222592340-f68f4ecd-1ccd-4553-9540-245e2ac6de4a.png"> _These don't go away when you quit the app._ ### Testcase Gist URL https://gist.github.com/PsychoLlama/fcb2790372b6e4957beac9be7e543d3d ### Additional Information I'm not very good with native code, but I think I've tracked it down. It appears to be similar to the bug described in `DockHide`: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/browser_mac.mm#L426-L434 The mechanism for hiding the dock is here: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/browser_mac.mm#L440-L444 It's pretty much the same implementation in `win.setVisibleOnAllWorkspaces`: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/native_window_mac.mm#L1291-L1292 `dock.hide()` avoids the bug by aborting if you call it within 1 second of calling `dock.show()`. Since `SetVisibleOnAllWorkspaces` doesn't have a guard, calling `dock.show()` can result in the same bug, creating an orphan dock icon for almost every window. --- Use case: We need to draw over windows we don't own, so we create a transparent overlay for each display. It's applied to every macOS space and has to render on top of fullscreen windows too: ```typescript win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, }) ``` Calling that method implicitly hides the dock icon (I understand that's an unavoidable behavior), but we can restore it with `app.dock.show()`. I called that method after creating an overlay. That's where I ran into the bug. If you have more than one display, we'll create multiple windows and call `dock.show()` multiple times, creating a race condition on the macOS APIs and generating duplicate dock icons.
https://github.com/electron/electron/issues/37487
https://github.com/electron/electron/pull/37599
7ed3c7a359c78c725ba02eaf5edd28968e356a32
eb613ef3d474f374874e5494a57bb06639811bdd
2023-03-03T00:54:47Z
c++
2023-03-20T14:30:49Z
shell/browser/native_window_mac.mm
// 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/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,487
[Bug]: Restoring dock icon after creating multiple overlay windows creates duplicates
### 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 23.1.1, 24.0.0-alpha.7, 25.0.0-nightly.20230302 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Creating several windows with `visibleOnFullScreen: true` and calling `app.dock.show()` should only show one icon in the dock. ### Actual Behavior Creating several windows with `visibleOnFullScreen: true` and calling `app.dock.show()` has a timing issue: it allows multiple dock icons to appear and detach, surviving even after you close the application. <img width="552" alt="screenshot: duplicate dock icons" src="https://user-images.githubusercontent.com/10053423/222592340-f68f4ecd-1ccd-4553-9540-245e2ac6de4a.png"> _These don't go away when you quit the app._ ### Testcase Gist URL https://gist.github.com/PsychoLlama/fcb2790372b6e4957beac9be7e543d3d ### Additional Information I'm not very good with native code, but I think I've tracked it down. It appears to be similar to the bug described in `DockHide`: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/browser_mac.mm#L426-L434 The mechanism for hiding the dock is here: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/browser_mac.mm#L440-L444 It's pretty much the same implementation in `win.setVisibleOnAllWorkspaces`: https://github.com/electron/electron/blob/ed7b5c44a2c7bfd57a44a04891452e967f07dd8e/shell/browser/native_window_mac.mm#L1291-L1292 `dock.hide()` avoids the bug by aborting if you call it within 1 second of calling `dock.show()`. Since `SetVisibleOnAllWorkspaces` doesn't have a guard, calling `dock.show()` can result in the same bug, creating an orphan dock icon for almost every window. --- Use case: We need to draw over windows we don't own, so we create a transparent overlay for each display. It's applied to every macOS space and has to render on top of fullscreen windows too: ```typescript win.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, }) ``` Calling that method implicitly hides the dock icon (I understand that's an unavoidable behavior), but we can restore it with `app.dock.show()`. I called that method after creating an overlay. That's where I ran into the bug. If you have more than one display, we'll create multiple windows and call `dock.show()` multiple times, creating a race condition on the macOS APIs and generating duplicate dock icons.
https://github.com/electron/electron/issues/37487
https://github.com/electron/electron/pull/37599
7ed3c7a359c78c725ba02eaf5edd28968e356a32
eb613ef3d474f374874e5494a57bb06639811bdd
2023-03-03T00:54:47Z
c++
2023-03-20T14:30:49Z
shell/browser/native_window_mac.mm
// 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/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/skia/include/core/SkRegion.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/base/hit_test.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" #include "ui/views/window/native_frame_view_mac.h" @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool hiddenInMissionControl = false; options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // The NSWindowStyleMaskFullSizeContentView style removes rounded corners // for frameless window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = NSWindowStyleMaskBorderless; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; SetHiddenInMissionControl(hiddenInMissionControl); // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. if ([window_ attachedSheet]) [window_ endSheet:[window_ attachedSheet]]; if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { NSRect frame = [window_ frame]; NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width, frame.size.height) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; [window setAlphaValue:0.5]; [window_ beginSheet:window completionHandler:^(NSModalResponse returnCode) { NSLog(@"main window disabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled)) return; // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen() || !IsFullScreenable()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; SetFullScreen(false); // Set presentation options *after* asynchronously exiting // fullscreen to ensure they take effect. [NSApp setPresentationOptions:kiosk_options_]; } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::InvalidateShadow() { [window_ invalidateShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } bool NativeWindowMac::IsHiddenInMissionControl() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorTransient; } void NativeWindowMac::SetHiddenInMissionControl(bool hidden) { SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient); } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetWindowButtonPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); } class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac { public: NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window) : views::NativeFrameViewMac(frame), native_window_(window) {} NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete; NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) = delete; ~NativeAppWindowFrameViewMac() override = default; // NonClientFrameView: int NonClientHitTest(const gfx::Point& point) override { if (!bounds().Contains(point)) return HTNOWHERE; if (GetWidget()->IsFullscreen()) return HTCLIENT; // Check for possible draggable region in the client area for the frameless // window. int contents_hit_test = native_window_->NonClientHitTest(point); if (contents_hit_test != HTNOWHERE) return contents_hit_test; return HTCLIENT; } private: // Weak. raw_ptr<NativeWindowMac> const native_window_; }; std::unique_ptr<views::NonClientFrameView> NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) { return std::make_unique<NativeAppWindowFrameViewMac>(widget, this); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
16,446
Widevine not working on Electron 4.0.1
I need Widevine on electron app I copied the widevinecdm.dll from Google Chrome. The CDM minimum version support is 68.0.3430.0 Widevine version 4.10.1224.7 On main.js `app.commandLine.appendSwitch('widevine-cdm-path', path.join(__dirname, 'widevinecdm.dll')); app.commandLine.appendSwitch('widevine-cdm-version', 4.10.1224.7);` and then `win = new BrowserWindow({ width:1000, height:800, webPreferences: { plugins: true} }); win.loadURL("http://www.dash-player.com/demo/drm-test-area/")` But this page shows NO Drm Support
https://github.com/electron/electron/issues/16446
https://github.com/electron/electron/pull/37583
caa5989eedd44625dad508c9665b8032df01e235
94f701edb8212d2bc5103bddc8077c5f5bcd2f6c
2019-01-18T13:54:14Z
c++
2023-03-20T17:33:08Z
package.json
{ "name": "electron", "version": "0.0.0-development", "repository": "https://github.com/electron/electron", "description": "Build cross platform desktop apps with JavaScript, HTML, and CSS", "devDependencies": { "@azure/storage-blob": "^12.9.0", "@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4", "@electron/asar": "^3.2.1", "@electron/docs-parser": "^1.1.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^1.5.0", "@electron/typescript-definitions": "^8.14.0", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", "@types/basic-auth": "^1.1.3", "@types/busboy": "^1.5.0", "@types/chai": "^4.2.12", "@types/chai-as-promised": "^7.1.3", "@types/dirty-chai": "^2.0.2", "@types/express": "^4.17.13", "@types/fs-extra": "^9.0.1", "@types/klaw": "^3.0.1", "@types/minimist": "^1.2.0", "@types/mocha": "^7.0.2", "@types/node": "^18.11.18", "@types/semver": "^7.3.3", "@types/send": "^0.14.5", "@types/split": "^1.0.0", "@types/stream-json": "^1.5.1", "@types/temp": "^0.8.34", "@types/uuid": "^3.4.6", "@types/webpack": "^5.28.0", "@types/webpack-env": "^1.17.0", "@typescript-eslint/eslint-plugin": "^4.4.1", "@typescript-eslint/parser": "^4.4.1", "aws-sdk": "^2.814.0", "buffer": "^6.0.3", "check-for-leaks": "^1.2.1", "colors": "1.4.0", "dotenv-safe": "^4.0.4", "dugite": "^2.3.0", "eslint": "^7.4.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.22.0", "eslint-plugin-mocha": "^7.0.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-standard": "^4.0.1", "eslint-plugin-typescript": "^0.14.0", "events": "^3.2.0", "express": "^4.16.4", "folder-hash": "^2.1.1", "fs-extra": "^9.0.1", "got": "^11.8.5", "husky": "^8.0.1", "klaw": "^3.0.0", "lint": "^1.1.2", "lint-staged": "^10.2.11", "markdownlint-cli": "^0.33.0", "mdast-util-from-markdown": "^1.2.0", "minimist": "^1.2.6", "null-loader": "^4.0.0", "pre-flight": "^1.1.0", "process": "^0.11.10", "remark-cli": "^10.0.0", "remark-preset-lint-markdown-style-guide": "^4.0.0", "semver": "^5.6.0", "shx": "^0.3.2", "standard-markdown": "^6.0.0", "stream-json": "^1.7.1", "tap-xunit": "^2.4.1", "temp": "^0.8.3", "timers-browserify": "1.4.2", "ts-loader": "^8.0.2", "ts-node": "6.2.0", "typescript": "^4.5.5", "unist-util-visit": "^4.1.1", "vscode-languageserver": "^8.0.2", "vscode-languageserver-textdocument": "^1.0.7", "vscode-uri": "^3.0.6", "webpack": "^5.73.0", "webpack-cli": "^4.10.0", "wrapper-webpack-plugin": "^2.2.0" }, "private": true, "scripts": { "asar": "asar", "generate-version-json": "node script/generate-version-json.js", "lint": "node ./script/lint.js && npm run lint:docs", "lint:js": "node ./script/lint.js --js", "lint:clang-format": "python3 script/run-clang-format.py -r -c shell/ || (echo \"\\nCode not formatted correctly.\" && exit 1)", "lint:clang-tidy": "ts-node ./script/run-clang-tidy.ts", "lint:cpp": "node ./script/lint.js --cc", "lint:objc": "node ./script/lint.js --objc", "lint:py": "node ./script/lint.js --py", "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-relative-links && npm run lint:markdownlint", "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs", "create-api-json": "node script/create-api-json.js", "create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js", "gn-typescript-definitions": "npm run create-typescript-definitions && shx cp electron.d.ts", "pre-flight": "pre-flight", "gn-check": "node ./script/gn-check.js", "gn-format": "python3 script/run-gn-format.py", "precommit": "lint-staged", "preinstall": "node -e 'process.exit(0)'", "prepack": "check-for-leaks", "prepare": "husky install", "repl": "node ./script/start.js --interactive", "start": "node ./script/start.js", "test": "node ./script/spec-runner.js", "tsc": "tsc", "webpack": "webpack" }, "license": "MIT", "author": "Electron Community", "keywords": [ "electron" ], "lint-staged": { "*.{js,ts}": [ "node script/lint.js --js --fix --only --" ], "*.{js,ts,d.ts}": [ "ts-node script/gen-filenames.ts" ], "*.{cc,mm,c,h}": [ "python3 script/run-clang-format.py -r -c --fix" ], "*.md": [ "npm run lint:docs" ], "*.{gn,gni}": [ "npm run gn-check", "npm run gn-format" ], "*.py": [ "node script/lint.js --py --fix --only --" ], "docs/api/**/*.md": [ "ts-node script/gen-filenames.ts", "markdownlint --config .markdownlint.autofix.json --fix", "git add filenames.auto.gni" ], "{*.patch,.patches}": [ "node script/lint.js --patches --only --", "ts-node script/check-patch-diff.ts" ], "DEPS": [ "node script/gen-hunspell-filenames.js", "node script/gen-libc++-filenames.js" ] }, "resolutions": { "nan": "nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac" } }
closed
electron/electron
https://github.com/electron/electron
16,446
Widevine not working on Electron 4.0.1
I need Widevine on electron app I copied the widevinecdm.dll from Google Chrome. The CDM minimum version support is 68.0.3430.0 Widevine version 4.10.1224.7 On main.js `app.commandLine.appendSwitch('widevine-cdm-path', path.join(__dirname, 'widevinecdm.dll')); app.commandLine.appendSwitch('widevine-cdm-version', 4.10.1224.7);` and then `win = new BrowserWindow({ width:1000, height:800, webPreferences: { plugins: true} }); win.loadURL("http://www.dash-player.com/demo/drm-test-area/")` But this page shows NO Drm Support
https://github.com/electron/electron/issues/16446
https://github.com/electron/electron/pull/37583
caa5989eedd44625dad508c9665b8032df01e235
94f701edb8212d2bc5103bddc8077c5f5bcd2f6c
2019-01-18T13:54:14Z
c++
2023-03-20T17:33:08Z
yarn.lock
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@azure/abort-controller@^1.0.0": version "1.0.4" resolved "https://registry.yarnpkg.com/@azure/abort-controller/-/abort-controller-1.0.4.tgz#fd3c4d46c8ed67aace42498c8e2270960250eafd" integrity sha512-lNUmDRVGpanCsiUN3NWxFTdwmdFI53xwhkTFfHDGTYk46ca7Ind3nanJc+U6Zj9Tv+9nTCWRBscWEW1DyKOpTw== dependencies: tslib "^2.0.0" "@azure/core-asynciterator-polyfill@^1.0.0": version "1.0.2" resolved "https://registry.yarnpkg.com/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.2.tgz#0dd3849fb8d97f062a39db0e5cadc9ffaf861fec" integrity sha512-3rkP4LnnlWawl0LZptJOdXNrT/fHp2eQMadoasa6afspXdpGrtPZuAQc2PD0cpgyuoXtUWyC3tv7xfntjGS5Dw== "@azure/core-auth@^1.3.0": version "1.3.2" resolved "https://registry.yarnpkg.com/@azure/core-auth/-/core-auth-1.3.2.tgz#6a2c248576c26df365f6c7881ca04b7f6d08e3d0" integrity sha512-7CU6DmCHIZp5ZPiZ9r3J17lTKMmYsm/zGvNkjArQwPkrLlZ1TZ+EUYfGgh2X31OLMVAQCTJZW4cXHJi02EbJnA== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/core-http@^2.0.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-http/-/core-http-2.2.4.tgz#df5a5b4138dbbc4299879f2fc6f257d0a5f0401e" integrity sha512-QmmJmexXKtPyc3/rsZR/YTLDvMatzbzAypJmLzvlfxgz/SkgnqV/D4f6F2LsK6tBj1qhyp8BoXiOebiej0zz3A== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-asynciterator-polyfill" "^1.0.0" "@azure/core-auth" "^1.3.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" "@types/node-fetch" "^2.5.0" "@types/tunnel" "^0.0.3" form-data "^4.0.0" node-fetch "^2.6.7" process "^0.11.10" tough-cookie "^4.0.0" tslib "^2.2.0" tunnel "^0.0.6" uuid "^8.3.0" xml2js "^0.4.19" "@azure/core-lro@^2.2.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-lro/-/core-lro-2.2.4.tgz#42fbf4ae98093c59005206a4437ddcd057c57ca1" integrity sha512-e1I2v2CZM0mQo8+RSix0x091Av493e4bnT22ds2fcQGslTHzM2oTbswkB65nP4iEpCxBrFxOSDPKExmTmjCVtQ== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" tslib "^2.2.0" "@azure/core-paging@^1.1.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@azure/core-paging/-/core-paging-1.2.1.tgz#1b884f563b6e49971e9a922da3c7a20931867b54" integrity sha512-UtH5iMlYsvg+nQYIl4UHlvvSrsBjOlRF4fs0j7mxd3rWdAStrKYrh2durOpHs5C9yZbVhsVDaisoyaf/lL1EVA== dependencies: "@azure/core-asynciterator-polyfill" "^1.0.0" tslib "^2.2.0" "@azure/[email protected]": version "1.0.0-preview.13" resolved "https://registry.yarnpkg.com/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz#55883d40ae2042f6f1e12b17dd0c0d34c536d644" integrity sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ== dependencies: "@opentelemetry/api" "^1.0.1" tslib "^2.2.0" "@azure/logger@^1.0.0": version "1.0.3" resolved "https://registry.yarnpkg.com/@azure/logger/-/logger-1.0.3.tgz#6e36704aa51be7d4a1bae24731ea580836293c96" integrity sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g== dependencies: tslib "^2.2.0" "@azure/storage-blob@^12.9.0": version "12.9.0" resolved "https://registry.yarnpkg.com/@azure/storage-blob/-/storage-blob-12.9.0.tgz#4cbd8b4c7a47dd064867430db892f4ef2d8f17ab" integrity sha512-ank38FdCLfJ+EoeMzCz3hkYJuZAd63ARvDKkxZYRDb+beBYf+/+gx8jNTqkq/hfyUl4dJQ/a7tECU0Y0F98CHg== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-http" "^2.0.0" "@azure/core-lro" "^2.2.0" "@azure/core-paging" "^1.1.1" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" events "^3.0.0" tslib "^2.2.0" "@babel/code-frame@^7.0.0": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw== dependencies: "@babel/highlight" "^7.0.0" "@babel/highlight@^7.0.0": version "7.5.0" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540" integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ== dependencies: chalk "^2.0.0" esutils "^2.0.2" js-tokens "^4.0.0" "@discoveryjs/json-ext@^0.5.0": version "0.5.7" resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== "@dsanders11/vscode-markdown-languageservice@^0.3.0-alpha.4": version "0.3.0-alpha.4" resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0-alpha.4.tgz#cd80b82142a2c10e09b5f36a93c3ea65b7d2a7f9" integrity sha512-MHp/CniEkzJb1CAw/bHwucuImaICrcIuohEFamTW8sJC2jhKCnbYblwJFZ3OOS3wTYZbzFIa8WZ4Dn5yL2E7jg== dependencies: "@vscode/l10n" "^0.0.10" picomatch "^2.3.1" vscode-languageserver-textdocument "^1.0.5" vscode-languageserver-types "^3.17.1" vscode-uri "^3.0.3" "@electron/asar@^3.2.1": version "3.2.1" resolved "https://registry.yarnpkg.com/@electron/asar/-/asar-3.2.1.tgz#c4143896f3dd43b59a80a9c9068d76f77efb62ea" integrity sha512-hE2cQMZ5+4o7+6T2lUaVbxIzrOjZZfX7dB02xuapyYFJZEAiWTelq6J3mMoxzd0iONDvYLPVKecB5tyjIoVDVA== dependencies: chromium-pickle-js "^0.2.0" commander "^5.0.0" glob "^7.1.6" minimatch "^3.0.4" optionalDependencies: "@types/glob" "^7.1.1" "@electron/docs-parser@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.1.0.tgz#ba095def41746bde56bee731feaf22272bf0b765" integrity sha512-qrjIKJk8t4/xAYldDVNQgcF8zdAAuG260bzPxdh/xI3p/yddm61bftoct+Tx2crnWFnOfOkr6nGERsDknNiT8A== dependencies: "@types/markdown-it" "^12.0.0" chai "^4.2.0" chalk "^3.0.0" fs-extra "^8.1.0" lodash.camelcase "^4.3.0" markdown-it "^12.0.0" minimist "^1.2.0" ora "^4.0.3" pretty-ms "^5.1.0" "@electron/fiddle-core@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@electron/fiddle-core/-/fiddle-core-1.0.4.tgz#d28e330c4d88f3916269558a43d214c4312333af" integrity sha512-gjPz3IAHK+/f0N52cWVeTZpdgENJo3QHBGeGqMDHFUgzSBRTVyAr8z8Lw8wpu6Ocizs154Rtssn4ba1ysABgLA== dependencies: "@electron/get" "^2.0.0" debug "^4.3.3" env-paths "^2.2.1" extract-zip "^2.0.1" fs-extra "^10.0.0" getos "^3.2.1" node-fetch "^2.6.1" semver "^7.3.5" simple-git "^3.5.0" "@electron/get@^2.0.0": version "2.0.2" resolved "https://registry.yarnpkg.com/@electron/get/-/get-2.0.2.tgz#ae2a967b22075e9c25aaf00d5941cd79c21efd7e" integrity sha512-eFZVFoRXb3GFGd7Ak7W4+6jBl9wBtiZ4AaYOse97ej6mKj5tkyO0dUnUChs1IhJZtx1BENo4/p4WUTXpi6vT+g== dependencies: debug "^4.1.1" env-paths "^2.2.0" fs-extra "^8.1.0" got "^11.8.5" progress "^2.0.3" semver "^6.2.0" sumchecker "^3.0.1" optionalDependencies: global-agent "^3.0.0" "@electron/github-app-auth@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@electron/github-app-auth/-/github-app-auth-1.5.0.tgz#426e64ba50143417d9b68f2795a1b119cb62108b" integrity sha512-t6Za+3E7jdIf1CX06nNV/avZhqSXNEkCLJ1xeAt5FKU9HdGbjzwSfirM+UlHO7lMGyuf13BGCZOCB1kODhDLWQ== dependencies: "@octokit/auth-app" "^3.6.1" "@octokit/rest" "^18.12.0" "@electron/typescript-definitions@^8.14.0": version "8.14.0" resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.14.0.tgz#a88f74e915317ba943b57ffe499b319d04f01ee3" integrity sha512-J3b4is6L0NB4+r+7s1Hl1YlzaveKnQt1gswadRyMRwb4gFU3VAe2oBMJLOhFRJMs/9PK/Xp+y9QwyC92Tyqe6A== dependencies: "@types/node" "^11.13.7" chalk "^2.4.2" colors "^1.1.2" debug "^4.1.1" fs-extra "^7.0.1" lodash "^4.17.11" minimist "^1.2.0" mkdirp "^0.5.1" ora "^3.4.0" pretty-ms "^5.0.0" "@jridgewell/gen-mapping@^0.3.0": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== dependencies: "@jridgewell/set-array" "^1.0.1" "@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/resolve-uri@^3.0.3": version "3.1.0" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== "@jridgewell/source-map@^0.3.2": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== dependencies: "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== "@jridgewell/trace-mapping@^0.3.7", "@jridgewell/trace-mapping@^0.3.9": version "0.3.14" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz#b231a081d8f66796e475ad588a1ef473112701ed" integrity sha512-bJWEfQ9lPTvm3SneWwRFVLzrh6nhjwqw7TUFFBEMzwvg7t7PCDenf2lDwqo4NQXzdpgBXyFgDWnQA+2vkruksQ== dependencies: "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" "@kwsites/file-exists@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/file-exists/-/file-exists-1.1.1.tgz#ad1efcac13e1987d8dbaf235ef3be5b0d96faa99" integrity sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw== dependencies: debug "^4.1.1" "@kwsites/promise-deferred@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz#8ace5259254426ccef57f3175bc64ed7095ed919" integrity sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw== "@nodelib/[email protected]": version "2.1.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b" integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw== dependencies: "@nodelib/fs.stat" "2.0.3" run-parallel "^1.1.9" "@nodelib/[email protected]", "@nodelib/fs.stat@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3" integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA== "@nodelib/fs.walk@^1.2.3": version "1.2.4" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976" integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ== dependencies: "@nodelib/fs.scandir" "2.1.3" fastq "^1.6.0" "@octokit/auth-app@^3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@octokit/auth-app/-/auth-app-3.6.1.tgz#aa5b02cc211175cbc28ce6c03c73373c1206d632" integrity sha512-6oa6CFphIYI7NxxHrdVOzhG7hkcKyGyYocg7lNDSJVauVOLtylg8hNJzoUyPAYKKK0yUeoZamE/lMs2tG+S+JA== dependencies: "@octokit/auth-oauth-app" "^4.3.0" "@octokit/auth-oauth-user" "^1.2.3" "@octokit/request" "^5.6.0" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.0.3" "@types/lru-cache" "^5.1.0" deprecation "^2.3.1" lru-cache "^6.0.0" universal-github-app-jwt "^1.0.1" universal-user-agent "^6.0.0" "@octokit/auth-oauth-app@^4.3.0": version "4.3.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-app/-/auth-oauth-app-4.3.4.tgz#7030955b1a59d4d977904775c606477d95fcfe8e" integrity sha512-OYOTSSINeUAiLMk1uelaGB/dEkReBqHHr8+hBejzMG4z1vA4c7QSvDAS0RVZSr4oD4PEUPYFzEl34K7uNrXcWA== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/auth-oauth-user" "^2.0.0" "@octokit/request" "^5.6.3" "@octokit/types" "^6.0.3" "@types/btoa-lite" "^1.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^3.1.1": version "3.1.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-3.1.4.tgz#703c42f27a1e2eb23498a7001ad8e9ecf4a2f477" integrity sha512-6sHE/++r+aEFZ/BKXOGPJcH/nbgbBjS1A4CHfq/PbPEwb0kZEt43ykW98GBO/rYBPAYaNpCPvXfGwzgR9yMCXg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^6.10.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^4.0.0": version "4.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.3.tgz#00ce77233517e0d7d39e42a02652f64337d9df81" integrity sha512-KPTx5nMntKjNZzzltO3X4T68v22rd7Cp/TcLJXQE2U8aXPcZ9LFuww9q9Q5WUNSu3jwi3lRwzfkPguRfz1R8Vg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^1.2.3": version "1.3.0" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-1.3.0.tgz#da4e4529145181a6aa717ae858afb76ebd6e3360" integrity sha512-3QC/TAdk7onnxfyZ24BnJRfZv8TRzQK7SEFUS9vLng4Vv6Hv6I64ujdk/CUkREec8lhrwU764SZ/d+yrjjqhaQ== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/oauth-methods" "^1.1.0" "@octokit/request" "^5.4.14" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-2.0.4.tgz#88f060ec678d7d493695af8d827e115dd064e212" integrity sha512-HrbDzTPqz6GcGSOUkR+wSeF3vEqsb9NMsmPja/qqqdiGmlk/Czkxctc3KeWYogHonp62Ml4kjz2VxKawrFsadQ== dependencies: "@octokit/auth-oauth-device" "^4.0.0" "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-token@^2.4.4": version "2.5.0" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36" integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g== dependencies: "@octokit/types" "^6.0.3" "@octokit/auth-token@^3.0.0": version "3.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-3.0.3.tgz#ce7e48a3166731f26068d7a7a7996b5da58cbe0c" integrity sha512-/aFM2M4HVDBT/jjDBa84sJniv1t9Gm/rLkalaz9htOm+L+8JMj1k9w0CkUdcxNyNxZPlTxKPVko+m1VlM58ZVA== dependencies: "@octokit/types" "^9.0.0" "@octokit/core@^3.5.1": version "3.6.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.6.0.tgz#3376cb9f3008d9b3d110370d90e0a1fcd5fe6085" integrity sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q== dependencies: "@octokit/auth-token" "^2.4.4" "@octokit/graphql" "^4.5.8" "@octokit/request" "^5.6.3" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.0.3" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/core@^4.1.0": version "4.2.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-4.2.0.tgz#8c253ba9605aca605bc46187c34fcccae6a96648" integrity sha512-AgvDRUg3COpR82P7PBdGZF/NNqGmtMq2NiPqeSsDIeCfYFOZ9gddqWNQHnFdEUf+YwOj4aZYmJnlPp7OXmDIDg== dependencies: "@octokit/auth-token" "^3.0.0" "@octokit/graphql" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^9.0.0" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^6.0.1": version "6.0.5" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.5.tgz#43a6adee813c5ffd2f719e20cfd14a1fee7c193a" integrity sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ== dependencies: "@octokit/types" "^5.0.0" is-plain-object "^4.0.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^7.0.0": version "7.0.3" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-7.0.3.tgz#0b96035673a9e3bedf8bab8f7335de424a2147ed" integrity sha512-57gRlb28bwTsdNXq+O3JTQ7ERmBTuik9+LelgcLIVfYwf235VHbN9QNo4kXExtp/h8T423cR5iJThKtFYxC7Lw== dependencies: "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" universal-user-agent "^6.0.0" "@octokit/graphql@^4.5.8": version "4.8.0" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3" integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg== dependencies: "@octokit/request" "^5.6.0" "@octokit/types" "^6.0.3" universal-user-agent "^6.0.0" "@octokit/graphql@^5.0.0": version "5.0.5" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-5.0.5.tgz#a4cb3ea73f83b861893a6370ee82abb36e81afd2" integrity sha512-Qwfvh3xdqKtIznjX9lz2D458r7dJPP8l6r4GQkIdWQouZwHQK0mVT88uwiU2bdTU2OtT1uOlKpRciUWldpG0yQ== dependencies: "@octokit/request" "^6.0.0" "@octokit/types" "^9.0.0" universal-user-agent "^6.0.0" "@octokit/oauth-authorization-url@^4.3.1": version "4.3.3" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-4.3.3.tgz#6a6ef38f243086fec882b62744f39b517528dfb9" integrity sha512-lhP/t0i8EwTmayHG4dqLXgU+uPVys4WD/qUNvC+HfB1S1dyqULm5Yx9uKc1x79aP66U1Cb4OZeW8QU/RA9A4XA== "@octokit/oauth-authorization-url@^5.0.0": version "5.0.0" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz#029626ce87f3b31addb98cd0d2355c2381a1c5a1" integrity sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg== "@octokit/oauth-methods@^1.1.0": version "1.2.6" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-1.2.6.tgz#b9ac65e374b2cc55ee9dd8dcdd16558550438ea7" integrity sha512-nImHQoOtKnSNn05uk2o76om1tJWiAo4lOu2xMAHYsNr0fwopP+Dv+2MlGvaMMlFjoqVd3fF3X5ZDTKCsqgmUaQ== dependencies: "@octokit/oauth-authorization-url" "^4.3.1" "@octokit/request" "^5.4.14" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" "@octokit/oauth-methods@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-2.0.4.tgz#6abd9593ca7f91fe5068375a363bd70abd5516dc" integrity sha512-RDSa6XL+5waUVrYSmOlYROtPq0+cfwppP4VaQY/iIei3xlFb0expH6YNsxNrZktcLhJWSpm9uzeom+dQrXlS3A== dependencies: "@octokit/oauth-authorization-url" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" "@octokit/openapi-types@^12.11.0": version "12.11.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.11.0.tgz#da5638d64f2b919bca89ce6602d059f1b52d3ef0" integrity sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ== "@octokit/openapi-types@^14.0.0": version "14.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-14.0.0.tgz#949c5019028c93f189abbc2fb42f333290f7134a" integrity sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw== "@octokit/openapi-types@^16.0.0": version "16.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-16.0.0.tgz#d92838a6cd9fb4639ca875ddb3437f1045cc625e" integrity sha512-JbFWOqTJVLHZSUUoF4FzAZKYtqdxWu9Z5m2QQnOyEa04fOFljvyh7D3GYKbfuaSWisqehImiVIMG4eyJeP5VEA== "@octokit/plugin-paginate-rest@^2.16.8": version "2.21.3" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz#7f12532797775640dbb8224da577da7dc210c87e" integrity sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw== dependencies: "@octokit/types" "^6.40.0" "@octokit/plugin-paginate-rest@^6.0.0": version "6.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.0.0.tgz#f34b5a7d9416019126042cd7d7b811e006c0d561" integrity sha512-Sq5VU1PfT6/JyuXPyt04KZNVsFOSBaYOAq2QRZUwzVlI10KFvcbUo8lR258AAQL1Et60b0WuVik+zOWKLuDZxw== dependencies: "@octokit/types" "^9.0.0" "@octokit/plugin-request-log@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85" integrity sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA== "@octokit/plugin-rest-endpoint-methods@^5.12.0": version "5.16.2" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz#7ee8bf586df97dd6868cf68f641354e908c25342" integrity sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw== dependencies: "@octokit/types" "^6.39.0" deprecation "^2.3.1" "@octokit/plugin-rest-endpoint-methods@^7.0.0": version "7.0.1" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.0.1.tgz#f7ebe18144fd89460f98f35a587b056646e84502" integrity sha512-pnCaLwZBudK5xCdrR823xHGNgqOzRnJ/mpC/76YPpNP7DybdsJtP7mdOwh+wYZxK5jqeQuhu59ogMI4NRlBUvA== dependencies: "@octokit/types" "^9.0.0" deprecation "^2.3.1" "@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0": version "2.1.0" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677" integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg== dependencies: "@octokit/types" "^6.0.3" deprecation "^2.0.0" once "^1.4.0" "@octokit/request-error@^3.0.0": version "3.0.2" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-3.0.2.tgz#f74c0f163d19463b87528efe877216c41d6deb0a" integrity sha512-WMNOFYrSaX8zXWoJg9u/pKgWPo94JXilMLb2VManNOby9EZxrQaBe/QSC4a1TzpAlpxofg2X/jMnCyZgL6y7eg== dependencies: "@octokit/types" "^8.0.0" deprecation "^2.0.0" once "^1.4.0" "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3": version "5.6.3" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0" integrity sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A== dependencies: "@octokit/endpoint" "^6.0.1" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.16.1" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/request@^6.0.0": version "6.2.2" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.2.tgz#a2ba5ac22bddd5dcb3f539b618faa05115c5a255" integrity sha512-6VDqgj0HMc2FUX2awIs+sM6OwLgwHvAi4KCK3mT2H2IKRt6oH9d0fej5LluF5mck1lRR/rFWN0YIDSYXYSylbw== dependencies: "@octokit/endpoint" "^7.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/rest@^18.12.0": version "18.12.0" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881" integrity sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q== dependencies: "@octokit/core" "^3.5.1" "@octokit/plugin-paginate-rest" "^2.16.8" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^5.12.0" "@octokit/rest@^19.0.7": version "19.0.7" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.7.tgz#d2e21b4995ab96ae5bfae50b4969da7e04e0bb70" integrity sha512-HRtSfjrWmWVNp2uAkEpQnuGMJsu/+dBr47dRc5QVgsCbnIc1+GFEaoKBWkYG+zjrsHpSqcAElMio+n10c0b5JA== dependencies: "@octokit/core" "^4.1.0" "@octokit/plugin-paginate-rest" "^6.0.0" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^7.0.0" "@octokit/types@^5.0.0": version "5.2.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.2.0.tgz#d075dc23bf293f540739250b6879e2c1be2fc20c" integrity sha512-XjOk9y4m8xTLIKPe1NFxNWBdzA2/z3PFFA/bwf4EoH6oS8hM0Y46mEa4Cb+KCyj/tFDznJFahzQ0Aj3o1FYq4A== dependencies: "@types/node" ">= 8" "@octokit/types@^6.0.3", "@octokit/types@^6.10.0", "@octokit/types@^6.12.2", "@octokit/types@^6.16.1", "@octokit/types@^6.39.0", "@octokit/types@^6.40.0": version "6.41.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.41.0.tgz#e58ef78d78596d2fb7df9c6259802464b5f84a04" integrity sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg== dependencies: "@octokit/openapi-types" "^12.11.0" "@octokit/types@^8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-8.0.0.tgz#93f0b865786c4153f0f6924da067fe0bb7426a9f" integrity sha512-65/TPpOJP1i3K4lBJMnWqPUJ6zuOtzhtagDvydAWbEXpbFYA0oMKKyLb95NFZZP0lSh/4b6K+DQlzvYQJQQePg== dependencies: "@octokit/openapi-types" "^14.0.0" "@octokit/types@^9.0.0": version "9.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-9.0.0.tgz#6050db04ddf4188ec92d60e4da1a2ce0633ff635" integrity sha512-LUewfj94xCMH2rbD5YJ+6AQ4AVjFYTgpp6rboWM5T7N3IsIF65SBEOVcYMGAEzO/kKNiNaW4LoWtoThOhH06gw== dependencies: "@octokit/openapi-types" "^16.0.0" "@opentelemetry/api@^1.0.1": version "1.0.4" resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.0.4.tgz#a167e46c10d05a07ab299fc518793b0cff8f6924" integrity sha512-BuJuXRSJNQ3QoKA6GWWDyuLpOUck+9hAXNMCnrloc1aWVoy6Xq6t9PUV08aBZ4Lutqq2LEHM486bpZqoViScog== "@primer/octicons@^10.0.0": version "10.0.0" resolved "https://registry.yarnpkg.com/@primer/octicons/-/octicons-10.0.0.tgz#81e94ed32545dfd3472c8625a5b345f3ea4c153d" integrity sha512-iuQubq62zXZjPmaqrsfsCZUqIJgZhmA6W0tKzIKGRbkoLnff4TFFCL87hfIRATZ5qZPM4m8ioT8/bXI7WVa9WQ== dependencies: object-assign "^4.1.1" "@sindresorhus/is@^4.0.0": version "4.6.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" integrity sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw== "@szmarczak/http-timer@^4.0.5": version "4.0.6" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-4.0.6.tgz#b4a914bb62e7c272d4e5989fe4440f812ab1d807" integrity sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w== dependencies: defer-to-connect "^2.0.0" "@types/basic-auth@^1.1.3": version "1.1.3" resolved "https://registry.yarnpkg.com/@types/basic-auth/-/basic-auth-1.1.3.tgz#a787ede8310804174fbbf3d6c623ab1ccedb02cd" integrity sha512-W3rv6J0IGlxqgE2eQ2pTb0gBjaGtejQpJ6uaCjz3UQ65+TFTPC5/lAE+POfx1YLdjtxvejJzsIAfd3MxWiVmfg== dependencies: "@types/node" "*" "@types/body-parser@*": version "1.19.0" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.0.tgz#0685b3c47eb3006ffed117cdd55164b61f80538f" integrity sha512-W98JrE0j2K78swW4ukqMleo8R7h/pFETjM2DQ90MF6XK2i4LO4W3gQ71Lt4w3bfm2EvVSyWHplECvB5sK22yFQ== dependencies: "@types/connect" "*" "@types/node" "*" "@types/btoa-lite@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/btoa-lite/-/btoa-lite-1.0.0.tgz#e190a5a548e0b348adb0df9ac7fa5f1151c7cca4" integrity sha512-wJsiX1tosQ+J5+bY5LrSahHxr2wT+uME5UDwdN1kg4frt40euqA+wzECkmq4t5QbveHiJepfdThgQrPw6KiSlg== "@types/busboy@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@types/busboy/-/busboy-1.5.0.tgz#62681556cbbd2afc8d2efa6bafaa15602f0838b9" integrity sha512-ncOOhwmyFDW76c/Tuvv9MA9VGYUCn8blzyWmzYELcNGDb0WXWLSmFi7hJq25YdRBYJrmMBB5jZZwUjlJe9HCjQ== dependencies: "@types/node" "*" "@types/cacheable-request@^6.0.1": version "6.0.2" resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.2.tgz#c324da0197de0a98a2312156536ae262429ff6b9" integrity sha512-B3xVo+dlKM6nnKTcmm5ZtY/OL8bOAOd2Olee9M1zft65ox50OzjEHW91sDiU9j6cvW8Ejg1/Qkf4xd2kugApUA== dependencies: "@types/http-cache-semantics" "*" "@types/keyv" "*" "@types/node" "*" "@types/responselike" "*" "@types/chai-as-promised@*": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.1.tgz#004c27a4ac640e9590e25d8b0980cb0a6609bfd8" integrity sha512-dberBxQW/XWv6BMj0su1lV9/C9AUx5Hqu2pisuS6S4YK/Qt6vurcj/BmcbEsobIWWCQzhesNY8k73kIxx4X7Mg== dependencies: "@types/chai" "*" "@types/chai-as-promised@^7.1.3": version "7.1.3" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.3.tgz#779166b90fda611963a3adbfd00b339d03b747bd" integrity sha512-FQnh1ohPXJELpKhzjuDkPLR2BZCAqed+a6xV4MI/T3XzHfd2FlarfUGUdZYgqYe8oxkYn0fchHEeHfHqdZ96sg== dependencies: "@types/chai" "*" "@types/chai@*": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.1.7.tgz#1b8e33b61a8c09cbe1f85133071baa0dbf9fa71a" integrity sha512-2Y8uPt0/jwjhQ6EiluT0XCri1Dbplr0ZxfFXUz+ye13gaqE8u5gL5ppao1JrUYr9cIip5S6MvQzBS7Kke7U9VA== "@types/chai@^4.2.12": version "4.2.12" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.2.12.tgz#6160ae454cd89dae05adc3bb97997f488b608201" integrity sha512-aN5IAC8QNtSUdQzxu7lGBgYAOuU1tmRU4c9dIq5OKGf/SBVjXo+ffM2wEjudAWbgpOhy60nLoAGH1xm8fpCKFQ== "@types/color-name@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== "@types/concat-stream@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/concat-stream/-/concat-stream-1.6.1.tgz#24bcfc101ecf68e886aaedce60dfd74b632a1b74" integrity sha512-eHE4cQPoj6ngxBZMvVf6Hw7Mh4jMW4U9lpGmS5GBPB9RYxlFg+CHaVN7ErNY4W9XfLIEn20b4VDYaIrbq0q4uA== dependencies: "@types/node" "*" "@types/connect@*": version "3.4.33" resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.33.tgz#31610c901eca573b8713c3330abc6e6b9f588546" integrity sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A== dependencies: "@types/node" "*" "@types/debug@^4.0.0": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg== dependencies: "@types/ms" "*" "@types/dirty-chai@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@types/dirty-chai/-/dirty-chai-2.0.2.tgz#eeac4802329a41ed7815ac0c1a6360335bf77d0c" integrity sha512-BruwIN/UQEU0ePghxEX+OyjngpOfOUKJQh3cmfeq2h2Su/g001iljVi3+Y2y2EFp3IPgjf4sMrRU33Hxv1FUqw== dependencies: "@types/chai" "*" "@types/chai-as-promised" "*" "@types/eslint-scope@^3.7.3": version "3.7.4" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16" integrity sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA== dependencies: "@types/eslint" "*" "@types/estree" "*" "@types/eslint@*": version "8.4.5" resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.4.5.tgz#acdfb7dd36b91cc5d812d7c093811a8f3d9b31e4" integrity sha512-dhsC09y1gpJWnK+Ff4SGvCuSnk9DaU0BJZSzOwa6GVSg65XtTugLBITDAAzRU5duGBoXBHpdR/9jHGxJjNflJQ== dependencies: "@types/estree" "*" "@types/json-schema" "*" "@types/estree@*": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.0.tgz#5fb2e536c1ae9bf35366eed879e827fa59ca41c2" integrity sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ== "@types/estree@^0.0.51": version "0.0.51" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== "@types/events@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" integrity sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig== dependencies: "@types/node" "*" "@types/qs" "*" "@types/range-parser" "*" "@types/express@^4.17.13": version "4.17.13" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.13.tgz#a76e2995728999bab51a33fabce1d705a3709034" integrity sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA== dependencies: "@types/body-parser" "*" "@types/express-serve-static-core" "^4.17.18" "@types/qs" "*" "@types/serve-static" "*" "@types/fs-extra@^9.0.1": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.1.tgz#91c8fc4c51f6d5dbe44c2ca9ab09310bd00c7918" integrity sha512-B42Sxuaz09MhC3DDeW5kubRcQ5by4iuVQ0cRRWM2lggLzAa/KVom0Aft/208NgMvNQQZ86s5rVcqDdn/SH0/mg== dependencies: "@types/node" "*" "@types/glob@^7.1.1": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" integrity sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w== dependencies: "@types/events" "*" "@types/minimatch" "*" "@types/node" "*" "@types/http-cache-semantics@*": version "4.0.1" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ== "@types/is-empty@^1.0.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/is-empty/-/is-empty-1.2.0.tgz#16bc578060c9b0b6953339eea906c255a375bf86" integrity sha512-brJKf2boFhUxTDxlpI7cstwiUtA2ovm38UzFTi9aZI6//ARncaV+Q5ALjCaJqXaMtdZk/oPTJnSutugsZR6h8A== "@types/js-yaml@^4.0.0": version "4.0.2" resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-4.0.2.tgz#4117a7a378593a218e9d6f0ef44ce6d5d9edf7fa" integrity sha512-KbeHS/Y4R+k+5sWXEYzAZKuB1yQlZtEghuhRxrVRLaqhtoG5+26JwQsa4HyS3AWX8v1Uwukma5HheduUDskasA== "@types/json-buffer@~3.0.0": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/json-buffer/-/json-buffer-3.0.0.tgz#85c1ff0f0948fc159810d4b5be35bf8c20875f64" integrity sha512-3YP80IxxFJB4b5tYC2SUPwkg0XQLiu0nWvhRgEatgjf+29IcWO9X1k8xRv5DGssJ/lCrjYTjQPcobJr2yWIVuQ== "@types/json-schema@*", "@types/json-schema@^7.0.8": version "7.0.11" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== "@types/json-schema@^7.0.3": version "7.0.3" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.3.tgz#bdfd69d61e464dcc81b25159c270d75a73c1a636" integrity sha512-Il2DtDVRGDcqjDtE+rF8iqg1CArehSK84HZJCT7AMITlyXRBpuPhqGLDQMowraqqu1coEaimg4ZOqggt6L6L+A== "@types/json-schema@^7.0.4": version "7.0.4" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339" integrity sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA== "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= "@types/jsonwebtoken@^9.0.0": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz#29b1369c4774200d6d6f63135bf3d1ba3ef997a4" integrity sha512-c5ltxazpWabia/4UzhIoaDcIza4KViOQhdbjRlfcIGVnsE3c3brkz9Z+F/EeJIECOQP7W7US2hNE930cWWkPiw== dependencies: "@types/node" "*" "@types/keyv@*": version "3.1.4" resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.4.tgz#3ccdb1c6751b0c7e52300bcdacd5bcbf8faa75b6" integrity sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg== dependencies: "@types/node" "*" "@types/klaw@^3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@types/klaw/-/klaw-3.0.1.tgz#29f90021c0234976aa4eb97efced9cb6db9fa8b3" integrity sha512-acnF3n9mYOr1aFJKFyvfNX0am9EtPUsYPq22QUCGdJE+MVt6UyAN1jwo+PmOPqXD4K7ZS9MtxDEp/un0lxFccA== dependencies: "@types/node" "*" "@types/linkify-it@*": version "2.1.0" resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-2.1.0.tgz#ea3dd64c4805597311790b61e872cbd1ed2cd806" integrity sha512-Q7DYAOi9O/+cLLhdaSvKdaumWyHbm7HAk/bFwwyTuU0arR5yyCeW5GOoqt4tJTpDRxhpx9Q8kQL6vMpuw9hDSw== "@types/lru-cache@^5.1.0": version "5.1.0" resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-5.1.0.tgz#57f228f2b80c046b4a1bd5cac031f81f207f4f03" integrity sha512-RaE0B+14ToE4l6UqdarKPnXwVDuigfFv+5j9Dze/Nqr23yyuqdNvzcZi3xB+3Agvi5R4EOgAksfv3lXX4vBt9w== "@types/markdown-it@^12.0.0": version "12.2.3" resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51" integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ== dependencies: "@types/linkify-it" "*" "@types/mdurl" "*" "@types/mdast@^3.0.0": version "3.0.7" resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.7.tgz#cba63d0cc11eb1605cea5c0ad76e02684394166b" integrity sha512-YwR7OK8aPmaBvMMUi+pZXBNoW2unbVbfok4YRqGMJBe1dpDlzpRkJrYEYmvjxgs5JhuQmKfDexrN98u941Zasg== dependencies: "@types/unist" "*" "@types/mdurl@*": version "1.0.2" resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9" integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA== "@types/mime@*": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-2.0.1.tgz#dc488842312a7f075149312905b5e3c0b054c79d" integrity sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw== "@types/mime@^1": version "1.3.2" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a" integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw== "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/minimist@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= "@types/mocha@^7.0.2": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-7.0.2.tgz#b17f16cf933597e10d6d78eae3251e692ce8b0ce" integrity sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w== "@types/ms@*": version "0.7.31" resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197" integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA== "@types/node-fetch@^2.5.0": version "2.6.1" resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.1.tgz#8f127c50481db65886800ef496f20bbf15518975" integrity sha512-oMqjURCaxoSIsHSr1E47QHzbmzNR5rK8McHuNb11BOM9cHcIK3Avy0s/b2JlXHoQGTYS3NsvWzV1M0iK7l0wbA== dependencies: "@types/node" "*" form-data "^3.0.0" "@types/node@*": version "12.6.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.1.tgz#d5544f6de0aae03eefbb63d5120f6c8be0691946" integrity sha512-rp7La3m845mSESCgsJePNL/JQyhkOJA6G4vcwvVgkDAwHhGdq5GCumxmPjEk1MZf+8p5ZQAUE7tqgQRQTXN7uQ== "@types/node@>= 8": version "14.0.27" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.27.tgz#a151873af5a5e851b51b3b065c9e63390a9e0eb1" integrity sha512-kVrqXhbclHNHGu9ztnAwSncIgJv/FaxmzXJvGXNdcCpV1b8u1/Mi6z6m0vwy0LzKeXFTPLH0NzwmoJ3fNCIq0g== "@types/node@^11.13.7": version "11.13.22" resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.22.tgz#91ee88ebfa25072433497f6f3150f84fa8c3a91b" integrity sha512-rOsaPRUGTOXbRBOKToy4cgZXY4Y+QSVhxcLwdEveozbk7yuudhWMpxxcaXqYizLMP3VY7OcWCFtx9lGFh5j5kg== "@types/node@^16.0.0": version "16.4.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d" integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg== "@types/node@^18.11.18": version "18.11.18" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.18.tgz#8dfb97f0da23c2293e554c5a50d61ef134d7697f" integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA== "@types/parse-json@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== "@types/qs@*": version "6.9.3" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" integrity sha512-7s9EQWupR1fTc2pSMtXRQ9w9gLOcrJn+h7HOXw4evxyvVqMi4f+q7d2tnFe3ng3SNHjtK+0EzGMGFUQX4/AQRA== "@types/range-parser@*": version "1.2.3" resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c" integrity sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA== "@types/repeat-string@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/repeat-string/-/repeat-string-1.6.1.tgz#8bb5686e662ce1d962271b0b043623bf51404cdc" integrity sha512-vdna8kjLGljgtPnYN6MBD2UwX62QE0EFLj9QlLXvg6dEu66NksXB900BNguBCMZZY2D9SSqncUskM23vT3uvWQ== "@types/responselike@*", "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA== dependencies: "@types/node" "*" "@types/semver@^7.3.3": version "7.3.3" resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.3.tgz#3ad6ed949e7487e7bda6f886b4a2434a2c3d7b1a" integrity sha512-jQxClWFzv9IXdLdhSaTf16XI3NYe6zrEbckSpb5xhKfPbWgIyAY0AFyWWWfaiDcBuj3UHmMkCIwSRqpKMTZL2Q== "@types/send@^0.14.5": version "0.14.5" resolved "https://registry.yarnpkg.com/@types/send/-/send-0.14.5.tgz#653f7d25b93c3f7f51a8994addaf8a229de022a7" integrity sha512-0mwoiK3DXXBu0GIfo+jBv4Wo5s1AcsxdpdwNUtflKm99VEMvmBPJ+/NBNRZy2R5JEYfWL/u4nAHuTUTA3wFecQ== dependencies: "@types/mime" "*" "@types/node" "*" "@types/serve-static@*": version "1.13.10" resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.13.10.tgz#f5e0ce8797d2d7cc5ebeda48a52c96c4fa47a8d9" integrity sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ== dependencies: "@types/mime" "^1" "@types/node" "*" "@types/split@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/split/-/split-1.0.0.tgz#24f7c35707450b002f203383228f5a2bc1e6c228" integrity sha512-pm9S1mkr+av0j7D6pFyqhBxXDbnbO9gqj4nb8DtGtCewvj0XhIv089SSwXrjrIizT1UquO8/h83hCut0pa3u8A== dependencies: "@types/node" "*" "@types/through" "*" "@types/stream-chain@*": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/stream-chain/-/stream-chain-2.0.0.tgz#aed7fc21ac3686bc721aebbbd971f5a857e567e4" integrity sha512-O3IRJcZi4YddlS8jgasH87l+rdNmad9uPAMmMZCfRVhumbWMX6lkBWnIqr9kokO5sx8LHp8peQ1ELhMZHbR0Gg== dependencies: "@types/node" "*" "@types/stream-json@^1.5.1": version "1.5.1" resolved "https://registry.yarnpkg.com/@types/stream-json/-/stream-json-1.5.1.tgz#ae8d1133f9f920e18c6e94b233cb57d014a47b8d" integrity sha512-Blg6GJbKVEB1J/y/2Tv+WrYiMzPTIqyuZ+zWDJtAF8Mo8A2XQh/lkSX4EYiM+qtS+GY8ThdGi6gGA9h4sjvL+g== dependencies: "@types/node" "*" "@types/stream-chain" "*" "@types/supports-color@^8.0.0": version "8.1.1" resolved "https://registry.yarnpkg.com/@types/supports-color/-/supports-color-8.1.1.tgz#1b44b1b096479273adf7f93c75fc4ecc40a61ee4" integrity sha512-dPWnWsf+kzIG140B8z2w3fr5D03TLWbOAFQl45xUpI3vcizeXriNR5VYkWZ+WTMsUHqZ9Xlt3hrxGNANFyNQfw== "@types/temp@^0.8.34": version "0.8.34" resolved "https://registry.yarnpkg.com/@types/temp/-/temp-0.8.34.tgz#03e4b3cb67cbb48c425bbf54b12230fef85540ac" integrity sha512-oLa9c5LHXgS6UimpEVp08De7QvZ+Dfu5bMQuWyMhf92Z26Q10ubEMOWy9OEfUdzW7Y/sDWVHmUaLFtmnX/2j0w== dependencies: "@types/node" "*" "@types/text-table@^0.2.0": version "0.2.2" resolved "https://registry.yarnpkg.com/@types/text-table/-/text-table-0.2.2.tgz#774c90cfcfbc8b4b0ebb00fecbe861dc8b1e8e26" integrity sha512-dGoI5Af7To0R2XE8wJuc6vwlavWARsCh3UKJPjWs1YEqGUqfgBI/j/4GX0yf19/DsDPPf0YAXWAp8psNeIehLg== "@types/through@*": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/through/-/through-0.0.29.tgz#72943aac922e179339c651fa34a4428a4d722f93" integrity sha512-9a7C5VHh+1BKblaYiq+7Tfc+EOmjMdZaD1MYtkQjSoxgB69tBjW98ry6SKsi4zEIWztLOMRuL87A3bdT/Fc/4w== dependencies: "@types/node" "*" "@types/tunnel@^0.0.3": version "0.0.3" resolved "https://registry.yarnpkg.com/@types/tunnel/-/tunnel-0.0.3.tgz#f109e730b072b3136347561fc558c9358bb8c6e9" integrity sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA== dependencies: "@types/node" "*" "@types/unist@*", "@types/unist@^2.0.0": version "2.0.6" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== "@types/unist@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e" integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ== "@types/uuid@^3.4.6": version "3.4.6" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.6.tgz#d2c4c48eb85a757bf2927f75f939942d521e3016" integrity sha512-cCdlC/1kGEZdEglzOieLDYBxHsvEOIg7kp/2FYyVR9Pxakq+Qf/inL3RKQ+PA8gOlI/NnL+fXmQH12nwcGzsHw== dependencies: "@types/node" "*" "@types/webpack-env@^1.17.0": version "1.17.0" resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0" integrity sha512-eHSaNYEyxRA5IAG0Ym/yCyf86niZUIF/TpWKofQI/CVfh5HsMEUyfE2kwFxha4ow0s5g0LfISQxpDKjbRDrizw== "@types/webpack@^5.28.0": version "5.28.0" resolved "https://registry.yarnpkg.com/@types/webpack/-/webpack-5.28.0.tgz#78dde06212f038d77e54116cfe69e88ae9ed2c03" integrity sha512-8cP0CzcxUiFuA9xGJkfeVpqmWTk9nx6CWwamRGCj95ph1SmlRRk9KlCZ6avhCbZd4L68LvYT6l1kpdEnQXrF8w== dependencies: "@types/node" "*" tapable "^2.2.0" webpack "^5" "@types/yauzl@^2.9.1": version "2.10.0" resolved "https://registry.yarnpkg.com/@types/yauzl/-/yauzl-2.10.0.tgz#b3248295276cf8c6f153ebe6a9aba0c988cb2599" integrity sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw== dependencies: "@types/node" "*" "@typescript-eslint/eslint-plugin@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.4.1.tgz#b8acea0373bd2a388ac47df44652f00bf8b368f5" integrity sha512-O+8Utz8pb4OmcA+Nfi5THQnQpHSD2sDUNw9AxNHpuYOo326HZTtG8gsfT+EAYuVrFNaLyNb2QnUNkmTRDskuRA== dependencies: "@typescript-eslint/experimental-utils" "4.4.1" "@typescript-eslint/scope-manager" "4.4.1" debug "^4.1.1" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.4.1.tgz#40613b9757fa0170de3e0043254dbb077cafac0c" integrity sha512-Nt4EVlb1mqExW9cWhpV6pd1a3DkUbX9DeyYsdoeziKOpIJ04S2KMVDO+SEidsXRH/XHDpbzXykKcMTLdTXH6cQ== dependencies: "@types/json-schema" "^7.0.3" "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" eslint-scope "^5.0.0" eslint-utils "^2.0.0" "@typescript-eslint/parser@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.4.1.tgz#25fde9c080611f303f2f33cedb145d2c59915b80" integrity sha512-S0fuX5lDku28Au9REYUsV+hdJpW/rNW0gWlc4SXzF/kdrRaAVX9YCxKpziH7djeWT/HFAjLZcnY7NJD8xTeUEg== dependencies: "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" debug "^4.1.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.4.1.tgz#d19447e60db2ce9c425898d62fa03b2cce8ea3f9" integrity sha512-2oD/ZqD4Gj41UdFeWZxegH3cVEEH/Z6Bhr/XvwTtGv66737XkR4C9IqEkebCuqArqBJQSj4AgNHHiN1okzD/wQ== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.4.1.tgz#c507b35cf523bc7ba00aae5f75ee9b810cdabbc1" integrity sha512-KNDfH2bCyax5db+KKIZT4rfA8rEk5N0EJ8P0T5AJjo5xrV26UAzaiqoJCxeaibqc0c/IvZxp7v2g3difn2Pn3w== "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.4.1.tgz#598f6de488106c2587d47ca2462c60f6e2797cb8" integrity sha512-wP/V7ScKzgSdtcY1a0pZYBoCxrCstLrgRQ2O9MmCUZDtmgxCO/TCqOTGRVwpP4/2hVfqMz/Vw1ZYrG8cVxvN3g== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" debug "^4.1.1" globby "^11.0.1" is-glob "^4.0.1" lodash "^4.17.15" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.4.1.tgz#1769dc7a9e2d7d2cfd3318b77ed8249187aed5c3" integrity sha512-H2JMWhLaJNeaylSnMSQFEhT/S/FsJbebQALmoJxMPMxLtlVAMy2uJP/Z543n9IizhjRayLSqoInehCeNW9rWcw== dependencies: "@typescript-eslint/types" "4.4.1" eslint-visitor-keys "^2.0.0" "@vscode/l10n@^0.0.10": version "0.0.10" resolved "https://registry.yarnpkg.com/@vscode/l10n/-/l10n-0.0.10.tgz#9c513107c690c0dd16e3ec61e453743de15ebdb0" integrity sha512-E1OCmDcDWa0Ya7vtSjp/XfHFGqYJfh+YPC1RkATU71fTac+j1JjCcB3qwSzmlKAighx2WxhLlfhS0RwAN++PFQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" integrity sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw== dependencies: "@webassemblyjs/helper-numbers" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz#f6c61a705f0fd7a6aecaa4e8198f23d9dc179e4f" integrity sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz#1a63192d8788e5c012800ba6a7a46c705288fd16" integrity sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz#832a900eb444884cde9a7cad467f81500f5e5ab5" integrity sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz#64d81da219fbbba1e3bd1bfc74f6e8c4e10a62ae" integrity sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ== dependencies: "@webassemblyjs/floating-point-hex-parser" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz#f328241e41e7b199d0b20c18e88429c4433295e1" integrity sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz#21ee065a7b635f319e738f0dd73bfbda281c097a" integrity sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz#963929e9bbd05709e7e12243a099180812992614" integrity sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ== dependencies: "@xtuc/ieee754" "^1.2.0" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.11.1.tgz#ce814b45574e93d76bae1fb2644ab9cdd9527aa5" integrity sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw== dependencies: "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.11.1.tgz#d1f8b764369e7c6e6bae350e854dec9a59f0a3ff" integrity sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz#ad206ebf4bf95a058ce9880a8c092c5dec8193d6" integrity sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/helper-wasm-section" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-opt" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/wast-printer" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz#86c5ea304849759b7d88c47a32f4f039ae3c8f76" integrity sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz#657b4c2202f4cf3b345f8a4c6461c8c2418985f2" integrity sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz#86ca734534f417e9bd3c67c7a1c75d8be41fb199" integrity sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz#d0c73beda8eec5426f10ae8ef55cee5e7084c2f0" integrity sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg== dependencies: "@webassemblyjs/ast" "1.11.1" "@xtuc/long" "4.2.2" "@webpack-cli/configtest@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== "@webpack-cli/info@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== dependencies: envinfo "^7.7.3" "@webpack-cli/serve@^1.7.0": version "1.7.0" resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== "@xtuc/ieee754@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== "@xtuc/[email protected]": version "4.2.2" resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw== dependencies: mime-types "~2.1.34" negotiator "0.6.3" acorn-import-assertions@^1.7.6: version "1.8.0" resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz#ba2b5939ce62c238db6d93d81c9b111b29b855e9" integrity sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw== acorn-jsx@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.2.0.tgz#4c66069173d6fdd68ed85239fc256226182b2ebe" integrity sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ== acorn@^7.1.1, acorn@^7.2.0: version "7.3.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.3.1.tgz#85010754db53c3fbaf3b9ea3e083aa5c5d147ffd" integrity sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA== acorn@^8.4.1, acorn@^8.5.0: version "8.7.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.7.1.tgz#0197122c843d1bf6d0a5e83220a788f278f63c30" integrity sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A== aggregate-error@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.0.1.tgz#db2fe7246e536f40d9b5442a39e117d7dd6a24e0" integrity sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA== dependencies: clean-stack "^2.0.0" indent-string "^4.0.0" ajv-keywords@^3.4.1: version "3.4.1" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== ajv-keywords@^3.5.2: version "3.5.2" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d" integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.2, ajv@^6.12.5: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== dependencies: fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" json-schema-traverse "^0.4.1" uri-js "^4.2.2" ansi-colors@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: version "4.3.1" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.1.tgz#a5c47cc43181f1f38ffd7076837700d395522a61" integrity sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA== dependencies: type-fest "^0.11.0" ansi-regex@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.1.tgz#164daac87ab2d6f6db3a29875e2d1766582dabed" integrity sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g== ansi-regex@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== ansi-regex@^6.0.0: version "6.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359" integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA== dependencies: "@types/color-name" "^1.1.1" color-convert "^2.0.1" anymatch@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.0.3.tgz#2fb624fe0e84bccab00afee3d0006ed310f22f09" integrity sha512-c6IvoeBECQlMVuYUjSwimnhmztImpErfxJzWZhIQinIvQWoGOnB0dLIgifbPHQt5heS6mNlaZG16f06H3C8t1g== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" integrity sha1-ml9pkFGx5wczKPKgCJaLZOopVdI= array-includes@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.0.3.tgz#184b48f62d92d7452bb31b323165c7f8bd02266d" integrity sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0= dependencies: define-properties "^1.1.2" es-abstract "^1.7.0" array-includes@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.1.tgz#cdd67e6852bdf9c1215460786732255ed2459348" integrity sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0" is-string "^1.0.5" array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= array.prototype.flat@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz#0de82b426b0318dbfdb940089e38b043d37f6c7b" integrity sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" arrify@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= assertion-error@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b" integrity sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw== astral-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg== astral-regex@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== async@^3.2.0: version "3.2.4" resolved "https://registry.yarnpkg.com/async/-/async-3.2.4.tgz#2d22e00f8cddeb5fde5dd33522b56d1cf569a81c" integrity sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ== asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= at-least-node@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== aws-sdk@^2.814.0: version "2.814.0" resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.814.0.tgz#7a1c36006e0b5826f14bd2511b1d229ef6814bb0" integrity sha512-empd1m/J/MAkL6d9OeRpmg9thobULu0wk4v8W3JToaxGi2TD7PIdvE6yliZKyOVAdJINhBWEBhxR4OUIHhcGbQ== dependencies: buffer "4.9.2" events "1.1.1" ieee754 "1.1.13" jmespath "0.15.0" querystring "0.2.0" sax "1.2.1" url "0.10.3" uuid "3.3.2" xml2js "0.4.19" bail@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/bail/-/bail-2.0.1.tgz#d676736373a374058a935aec81b94c12ba815771" integrity sha512-d5FoTAr2S5DSUPKl85WNm2yUwsINN8eidIdIwsOge2t33DaOfOdSmmsI11jMN3GmALCXaw+Y6HMVHDzePshFAA== balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== base64-js@^1.0.2: version "1.3.0" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.0.tgz#cab1e6118f051095e58b5281aea8c1cd22bfc0e3" integrity sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw== base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== before-after-hook@^2.2.0: version "2.2.3" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.3.tgz#c51e809c81a4e354084422b9b26bad88249c517c" integrity sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ== big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== binary-extensions@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== [email protected]: version "1.20.1" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.1.tgz#b1812a8912c195cd371a3ee5e66faa2338a5c668" integrity sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw== dependencies: bytes "3.1.2" content-type "~1.0.4" debug "2.6.9" depd "2.0.0" destroy "1.2.0" http-errors "2.0.0" iconv-lite "0.4.24" on-finished "2.4.1" qs "6.11.0" raw-body "2.5.1" type-is "~1.6.18" unpipe "1.0.0" boolean@^3.0.1: version "3.2.0" resolved "https://registry.yarnpkg.com/boolean/-/boolean-3.2.0.tgz#9e5294af4e98314494cbb17979fa54ca159f116b" integrity sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" brace-expansion@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" braces@^3.0.1, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: fill-range "^7.0.1" browserslist@^4.14.5: version "4.21.2" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.2.tgz#59a400757465535954946a400b841ed37e2b4ecf" integrity sha512-MonuOgAtUB46uP5CezYbRaYKBNt2LxP0yX+Pmj4LkcDFGkn9Cbpi83d9sCjwQDErXsIJSzY5oKGDbgOlF/LPAA== dependencies: caniuse-lite "^1.0.30001366" electron-to-chromium "^1.4.188" node-releases "^2.0.6" update-browserslist-db "^1.0.4" btoa-lite@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/btoa-lite/-/btoa-lite-1.0.0.tgz#337766da15801210fdd956c22e9c6891ab9d0337" integrity sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA== buffer-crc32@~0.2.3: version "0.2.13" resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" integrity sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ== [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk= buffer-from@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== buffer-from@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== [email protected]: version "4.9.2" resolved "https://registry.yarnpkg.com/buffer/-/buffer-4.9.2.tgz#230ead344002988644841ab0244af8c44bbe3ef8" integrity sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg== dependencies: base64-js "^1.0.2" ieee754 "^1.1.4" isarray "^1.0.0" buffer@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== dependencies: base64-js "^1.3.1" ieee754 "^1.2.1" builtins@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/builtins/-/builtins-4.0.0.tgz#a8345420de82068fdc4d6559d0456403a8fb1905" integrity sha512-qC0E2Dxgou1IHhvJSLwGDSTvokbRovU5zZFuDY6oY8Y2lF3nGt5Ad8YZK7GMtqzY84Wu7pXTPeHQeHcXSXsRhw== dependencies: semver "^7.0.0" [email protected]: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== cacheable-lookup@^5.0.3: version "5.0.4" resolved "https://registry.yarnpkg.com/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz#5a6b865b2c44357be3d5ebc2a467b032719a7005" integrity sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA== cacheable-request@^7.0.2: version "7.0.2" resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-7.0.2.tgz#ea0d0b889364a25854757301ca12b2da77f91d27" integrity sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew== dependencies: clone-response "^1.0.2" get-stream "^5.1.0" http-cache-semantics "^4.0.0" keyv "^4.0.0" lowercase-keys "^2.0.0" normalize-url "^6.0.1" responselike "^2.0.0" call-bind@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== dependencies: function-bind "^1.1.1" get-intrinsic "^1.0.2" callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== camelcase@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== caniuse-lite@^1.0.30001366: version "1.0.30001367" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001367.tgz#2b97fe472e8fa29c78c5970615d7cd2ee414108a" integrity sha512-XDgbeOHfifWV3GEES2B8rtsrADx4Jf+juKX2SICJcaUhjYBO3bR96kvEIHa15VU6ohtOhBZuPGGYGbXMRn0NCw== chai@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/chai/-/chai-4.2.0.tgz#760aa72cf20e3795e84b12877ce0e83737aa29e5" integrity sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw== dependencies: assertion-error "^1.1.0" check-error "^1.0.2" deep-eql "^3.0.1" get-func-name "^2.0.0" pathval "^1.1.0" type-detect "^4.0.5" chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" chalk@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" chalk@^4.0.0, chalk@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" character-entities-legacy@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz#57f4d00974c696e8f74e9f493e7fcb75b44d7ee7" integrity sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA== character-entities@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-2.0.0.tgz#508355fcc8c73893e0909efc1a44d28da2b6fdf3" integrity sha512-oHqMj3eAuJ77/P5PaIRcqk+C3hdfNwyCD2DAUcD5gyXkegAuF2USC40CEqPscDk4I8FRGMTojGJQkXDsN5QlJA== character-reference-invalid@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-2.0.0.tgz#a0bdeb89c051fe7ed5d3158b2f06af06984f2813" integrity sha512-pE3Z15lLRxDzWJy7bBHBopRwfI20sbrMVLQTC7xsPglCHf4Wv1e167OgYAFP78co2XlhojDyAqA+IAJse27//g== chardet@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== check-error@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= check-for-leaks@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/check-for-leaks/-/check-for-leaks-1.2.1.tgz#4ac108ee3f8e6b99f5ad36f6b98cba1d7f4816d0" integrity sha512-9OdOSRZY6N0w5JCdJpqsC5MkD6EPGYpHmhtf4l5nl3DRETDZshP6C1EGN/vVhHDTY6AsOK3NhdFfrMe3NWZl7g== dependencies: anymatch "^3.0.2" minimist "^1.2.0" parse-gitignore "^0.4.0" walk-sync "^0.3.2" chokidar@^3.0.0: version "3.5.2" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== dependencies: anymatch "~3.1.2" braces "~3.0.2" glob-parent "~5.1.2" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" readdirp "~3.6.0" optionalDependencies: fsevents "~2.3.2" chownr@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== chrome-trace-event@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" integrity sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ== dependencies: tslib "^1.9.0" chromium-pickle-js@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz#04a106672c18b085ab774d983dfa3ea138f22205" integrity sha1-BKEGZywYsIWrd02YPfo+oTjyIgU= clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== cli-cursor@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" integrity sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU= dependencies: restore-cursor "^2.0.0" cli-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== dependencies: restore-cursor "^3.1.0" cli-spinners@^2.0.0, cli-spinners@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== [email protected], cli-truncate@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== dependencies: slice-ansi "^3.0.0" string-width "^4.2.0" cli-width@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" integrity sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw== clone-deep@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== dependencies: is-plain-object "^2.0.4" kind-of "^6.0.2" shallow-clone "^3.0.0" clone-response@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.2.tgz#d1dc973920314df67fbeb94223b4ee350239e96b" integrity sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws= dependencies: mimic-response "^1.0.0" clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4= [email protected]: version "3.1.0" resolved "https://registry.yarnpkg.com/co/-/co-3.1.0.tgz#4ea54ea5a08938153185e15210c68d9092bc1b78" integrity sha1-TqVOpaCJOBUxheFSEMaNkJK8G3g= color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-convert@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== dependencies: color-name "~1.1.4" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= color-name@~1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== colorette@^2.0.14: version "2.0.19" resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== [email protected]: version "1.4.0" resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== colors@^1.1.2: version "1.3.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.3.tgz#39e005d546afe01e01f9c4ca8fa50f686a01205d" integrity sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg== combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== dependencies: delayed-stream "~1.0.0" commander@^2.20.0, commander@^2.9.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== commander@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== commander@^5.0.0, commander@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== commander@^7.0.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== commander@~9.4.1: version "9.4.1" resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.1.tgz#d1dd8f2ce6faf93147295c0df13c7c21141cfbdd" integrity sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw== compress-brotli@^1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/compress-brotli/-/compress-brotli-1.3.8.tgz#0c0a60c97a989145314ec381e84e26682e7b38db" integrity sha512-lVcQsjhxhIXsuupfy9fmZUFtAIdBmXA7EGY6GBdgZ++qkM9zG4YFT8iU7FoBxzryNDMOpD1HIFHUSX4D87oqhQ== dependencies: "@types/json-buffer" "~3.0.0" json-buffer "~3.0.1" [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== concat-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-2.0.0.tgz#414cf5af790a48c60ab9be4527d56d5e41133cb1" integrity sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A== dependencies: buffer-from "^1.0.0" inherits "^2.0.3" readable-stream "^3.0.2" typedarray "^0.0.6" contains-path@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo= [email protected]: version "0.5.4" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== dependencies: safe-buffer "5.2.1" content-type@~1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA== [email protected]: version "1.0.6" resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw= [email protected]: version "0.5.0" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b" integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw== core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= cosmiconfig@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982" integrity sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg== dependencies: "@types/parse-json" "^4.0.0" import-fresh "^3.1.0" parse-json "^5.0.0" path-type "^4.0.0" yaml "^1.7.2" cross-spawn@^6.0.5: version "6.0.5" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== dependencies: nice-try "^1.0.4" path-key "^2.0.1" semver "^5.5.0" shebang-command "^1.2.0" which "^1.2.9" cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== dependencies: path-key "^3.1.0" shebang-command "^2.0.0" which "^2.0.1" debug-log@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f" integrity sha1-IwdjLUwEOCuN+KMvcLiVBG1SdF8= [email protected], debug@^2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" debug@^3.1.0: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" debug@^4.0.0: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== dependencies: ms "2.1.2" debug@^4.0.1, debug@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== dependencies: ms "^2.1.1" debug@^4.1.0, debug@^4.3.3, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" decode-named-character-reference@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz#daabac9690874c394c81e4162a0304b35d824f0e" integrity sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg== dependencies: character-entities "^2.0.0" decompress-response@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== dependencies: mimic-response "^3.1.0" dedent@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw= deep-eql@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df" integrity sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw== dependencies: type-detect "^4.0.0" deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== deep-is@^0.1.3, deep-is@~0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= defaults@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.3.tgz#c656051e9817d9ff08ed881477f3fe4019f3ef7d" integrity sha1-xlYFHpgX2f8I7YgUd/P+QBnz730= dependencies: clone "^1.0.2" defer-to-connect@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587" integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg== define-properties@^1.1.2, define-properties@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" deglob@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/deglob/-/deglob-4.0.1.tgz#0685c6383992fd6009be10653a2b1116696fad55" integrity sha512-/g+RDZ7yf2HvoW+E5Cy+K94YhgcFgr6C8LuHZD1O5HoNPkf3KY6RfXJ0DBGlB/NkLi5gml+G9zqRzk9S0mHZCg== dependencies: find-root "^1.0.0" glob "^7.0.5" ignore "^5.0.0" pkg-config "^1.1.0" run-parallel "^1.1.2" uniq "^1.0.1" delayed-stream@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== dequal@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== detect-node@^2.0.4: version "2.1.0" resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== diff@^3.1.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== diff@^5.0.0: version "5.1.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.1.0.tgz#bc52d298c5ea8df9194800224445ed43ffc87e40" integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== dependencies: path-type "^4.0.0" [email protected]: version "1.5.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" integrity sha1-N53Ocw9hZvds76TmcHoVmwLFpvo= dependencies: esutils "^2.0.2" isarray "^1.0.0" doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" integrity sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw== dependencies: esutils "^2.0.2" doctrine@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== dependencies: esutils "^2.0.2" dotenv-safe@^4.0.4: version "4.0.4" resolved "https://registry.yarnpkg.com/dotenv-safe/-/dotenv-safe-4.0.4.tgz#8b0e7ced8e70b1d3c5d874ef9420e406f39425b3" integrity sha1-iw587Y5wsdPF2HTvlCDkBvOUJbM= dependencies: dotenv "^4.0.0" dotenv@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-4.0.0.tgz#864ef1379aced55ce6f95debecdce179f7a0cd1d" integrity sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0= dugite@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/dugite/-/dugite-2.3.0.tgz#ff6fdb4c899f84ed6695c9e01eaf4364a6211f13" integrity sha512-78zuD3p5lx2IS8DilVvHbXQXRo+hGIb3EAshTEC3ZyBLyArKegA8R/6c4Ne1aUlx6JRf3wmKNgYkdJOYMyj9aA== dependencies: progress "^2.0.3" tar "^6.1.11" duplexer@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= [email protected]: version "1.0.11" resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf" integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ== dependencies: safe-buffer "^5.0.1" [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.188: version "1.4.195" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.195.tgz#139b2d95a42a3f17df217589723a1deac71d1473" integrity sha512-vefjEh0sk871xNmR5whJf9TEngX+KTKS3hOHpjoMpauKkwlGwtMz1H8IaIjAT/GNnX0TbGwAdmVoXCAzXf+PPg== emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== emoji-regex@^9.2.2: version "9.2.2" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" integrity sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q== encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= end-of-stream@^1.1.0: version "1.4.4" resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" enhanced-resolve@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" integrity sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng== dependencies: graceful-fs "^4.1.2" memory-fs "^0.4.0" tapable "^1.0.0" enhanced-resolve@^5.9.3: version "5.10.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz#0dc579c3bb2a1032e357ac45b8f3a6f3ad4fb1e6" integrity sha512-T0yTFjdpldGY8PmuXXR0PyQ1ufZpEGiHVrp7zHKB7jdR4qlmZHhONVM5AQOAWXuF/w3dnHbEQVrNptJgt7F+cQ== dependencies: graceful-fs "^4.2.4" tapable "^2.2.0" enquirer@^2.3.5: version "2.3.6" resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== dependencies: ansi-colors "^4.1.1" ensure-posix-path@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/ensure-posix-path/-/ensure-posix-path-1.1.1.tgz#3c62bdb19fa4681544289edb2b382adc029179ce" integrity sha512-VWU0/zXzVbeJNXvME/5EmLuEj2TauvoaTz6aFYK1Z92JCBlDlZ3Gu0tuGR42kpW1754ywTs+QB0g5TP0oj9Zaw== entities@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== entities@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== env-paths@^2.2.0, env-paths@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== envinfo@^7.7.3: version "7.8.1" resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== errno@^0.1.3: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== dependencies: prr "~1.0.1" error-ex@^1.2.0, error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" es-abstract@^1.17.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.5: version "1.17.6" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" is-callable "^1.2.0" is-regex "^1.1.0" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" string.prototype.trimend "^1.0.1" string.prototype.trimstart "^1.0.1" es-abstract@^1.7.0: version "1.13.0" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9" integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg== dependencies: es-to-primitive "^1.2.0" function-bind "^1.1.1" has "^1.0.3" is-callable "^1.1.4" is-regex "^1.0.4" object-keys "^1.0.12" es-module-lexer@^0.9.0: version "0.9.3" resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== es-to-primitive@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es-to-primitive@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es6-error@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/es6-error/-/es6-error-4.1.1.tgz#9e3af407459deed47e9a91f9b885a84eb05c561d" integrity sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg== es6-object-assign@^1.0.3: version "1.1.0" resolved "https://registry.yarnpkg.com/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= escape-string-regexp@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== [email protected]: version "8.1.0" resolved "https://registry.yarnpkg.com/eslint-config-standard-jsx/-/eslint-config-standard-jsx-8.1.0.tgz#314c62a0e6f51f75547f89aade059bec140edfc7" integrity sha512-ULVC8qH8qCqbU792ZOO6DaiaZyHNS/5CZt3hKqHkEhVlhPEPN3nfBqqxJCyp59XrjIBZPu1chMYe9T2DXZ7TMw== [email protected], eslint-config-standard@^14.1.1: version "14.1.1" resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-14.1.1.tgz#830a8e44e7aef7de67464979ad06b406026c56ea" integrity sha512-Z9B+VR+JIXRxz21udPTL9HpFMyoMUEeX1G251EQ6e05WD9aPVtVBn09XUmZ259wCMlCDmYDSZG62Hhm+ZTJcUg== eslint-import-resolver-node@^0.3.2, eslint-import-resolver-node@^0.3.3: version "0.3.4" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz#85ffa81942c25012d8231096ddf679c03042c717" integrity sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA== dependencies: debug "^2.6.9" resolve "^1.13.1" eslint-module-utils@^2.4.0, eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" integrity sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA== dependencies: debug "^2.6.9" pkg-dir "^2.0.0" eslint-plugin-es@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-2.0.0.tgz#0f5f5da5f18aa21989feebe8a73eadefb3432976" integrity sha512-f6fceVtg27BR02EYnBhgWLFQfK6bN4Ll0nQFrBHOlCsAyxeZkn0NHns5O0YZOPrV1B3ramd6cgFwaoFLcSkwEQ== dependencies: eslint-utils "^1.4.2" regexpp "^3.0.0" eslint-plugin-es@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz#75a7cdfdccddc0589934aeeb384175f221c57893" integrity sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ== dependencies: eslint-utils "^2.0.0" regexpp "^3.0.0" eslint-plugin-import@^2.22.0: version "2.22.0" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz#92f7736fe1fde3e2de77623c838dd992ff5ffb7e" integrity sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg== dependencies: array-includes "^3.1.1" array.prototype.flat "^1.2.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.3" eslint-module-utils "^2.6.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.1" read-pkg-up "^2.0.0" resolve "^1.17.0" tsconfig-paths "^3.9.0" eslint-plugin-import@~2.18.0: version "2.18.2" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.18.2.tgz#02f1180b90b077b33d447a17a2326ceb400aceb6" integrity sha512-5ohpsHAiUBRNaBWAF08izwUGlbrJoJJ+W9/TBwsGoR1MnlgfwMIKrFeSjWbt6moabiXW9xNvtFz+97KHRfI4HQ== dependencies: array-includes "^3.0.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.2" eslint-module-utils "^2.4.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.0" read-pkg-up "^2.0.0" resolve "^1.11.0" eslint-plugin-mocha@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-mocha/-/eslint-plugin-mocha-7.0.1.tgz#b2e9e8ebef7836f999a83f8bab25d0e0c05f0d28" integrity sha512-zkQRW9UigRaayGm/pK9TD5RjccKXSgQksNtpsXbG9b6L5I+jNx7m98VUbZ4w1H1ArlNA+K7IOH+z8TscN6sOYg== dependencies: eslint-utils "^2.0.0" ramda "^0.27.0" eslint-plugin-node@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" integrity sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g== dependencies: eslint-plugin-es "^3.0.0" eslint-utils "^2.0.0" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-node@~10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-10.0.0.tgz#fd1adbc7a300cf7eb6ac55cf4b0b6fc6e577f5a6" integrity sha512-1CSyM/QCjs6PXaT18+zuAXsjXGIGo5Rw630rSKwokSs2jrYURQc4R5JZpoanNCqwNmepg+0eZ9L7YiRUJb8jiQ== dependencies: eslint-plugin-es "^2.0.0" eslint-utils "^1.4.2" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-promise@~4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz#845fd8b2260ad8f82564c1222fce44ad71d9418a" integrity sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw== eslint-plugin-react@~7.14.2: version "7.14.3" resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz#911030dd7e98ba49e1b2208599571846a66bdf13" integrity sha512-EzdyyBWC4Uz2hPYBiEJrKCUi2Fn+BJ9B/pJQcjw5X+x/H2Nm59S4MJIvL4O5NEE0+WbnQwEBxWY03oUk+Bc3FA== dependencies: array-includes "^3.0.3" doctrine "^2.1.0" has "^1.0.3" jsx-ast-utils "^2.1.0" object.entries "^1.1.0" object.fromentries "^2.0.0" object.values "^1.1.0" prop-types "^15.7.2" resolve "^1.10.1" eslint-plugin-standard@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.1.tgz#ff0519f7ffaff114f76d1bd7c3996eef0f6e20b4" integrity sha512-v/KBnfyaOMPmZc/dmc6ozOdWqekGp7bBGq4jLAecEfPGmfKiWS4sA8sC0LqiV9w5qmXAtXVn4M3p1jSyhY85SQ== eslint-plugin-standard@~4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.0.tgz#f845b45109c99cd90e77796940a344546c8f6b5c" integrity sha512-OwxJkR6TQiYMmt1EsNRMe5qG3GsbjlcOhbGUBY4LtavF9DsLaTcoR+j2Tdjqi23oUwKNUqX7qcn5fPStafMdlA== eslint-plugin-typescript@^0.14.0: version "0.14.0" resolved "https://registry.yarnpkg.com/eslint-plugin-typescript/-/eslint-plugin-typescript-0.14.0.tgz#068549c3f4c7f3f85d88d398c29fa96bf500884c" integrity sha512-2u1WnnDF2mkWWgU1lFQ2RjypUlmRoBEvQN02y9u+IL12mjWlkKFGEBnVsjs9Y8190bfPQCvWly1c2rYYUSOxWw== dependencies: requireindex "~1.1.0" [email protected]: version "5.1.1" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== dependencies: esrecurse "^4.3.0" estraverse "^4.1.1" eslint-scope@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.0.0.tgz#e87c8887c73e8d1ec84f1ca591645c358bfc8fb9" integrity sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw== dependencies: esrecurse "^4.1.0" estraverse "^4.1.1" eslint-scope@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.0.tgz#d0f971dfe59c69e0cada684b23d49dbf82600ce5" integrity sha512-iiGRvtxWqgtx5m8EyQUJihBloE4EnYeGE/bz1wSPwJE6tZuJUtHlhqDM4Xj2ukE8Dyy1+HCZ4hE0fzIVMzb58w== dependencies: esrecurse "^4.1.0" estraverse "^4.1.1" eslint-utils@^1.4.2, eslint-utils@^1.4.3: version "1.4.3" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f" integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q== dependencies: eslint-visitor-keys "^1.1.0" eslint-utils@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" eslint-visitor-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2" integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A== eslint-visitor-keys@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== eslint-visitor-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8" integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== eslint@^7.4.0: version "7.4.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.4.0.tgz#4e35a2697e6c1972f9d6ef2b690ad319f80f206f" integrity sha512-gU+lxhlPHu45H3JkEGgYhWhkR9wLHHEXC9FbWFnTlEkbKyZKWgWRLgf61E8zWmBuI6g5xKBph9ltg3NtZMVF8g== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^4.0.0" cross-spawn "^7.0.2" debug "^4.0.1" doctrine "^3.0.0" enquirer "^2.3.5" eslint-scope "^5.1.0" eslint-utils "^2.0.0" eslint-visitor-keys "^1.2.0" espree "^7.1.0" esquery "^1.2.0" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash "^4.17.14" minimatch "^3.0.4" natural-compare "^1.4.0" optionator "^0.9.1" progress "^2.0.0" regexpp "^3.1.0" semver "^7.2.1" strip-ansi "^6.0.0" strip-json-comments "^3.1.0" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" eslint@~6.8.0: version "6.8.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-6.8.0.tgz#62262d6729739f9275723824302fb227c8c93ffb" integrity sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^2.1.0" cross-spawn "^6.0.5" debug "^4.0.1" doctrine "^3.0.0" eslint-scope "^5.0.0" eslint-utils "^1.4.3" eslint-visitor-keys "^1.1.0" espree "^6.1.2" esquery "^1.0.1" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" inquirer "^7.0.0" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.3.0" lodash "^4.17.14" minimatch "^3.0.4" mkdirp "^0.5.1" natural-compare "^1.4.0" optionator "^0.8.3" progress "^2.0.0" regexpp "^2.0.1" semver "^6.1.2" strip-ansi "^5.2.0" strip-json-comments "^3.0.1" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" espree@^6.1.2: version "6.2.1" resolved "https://registry.yarnpkg.com/espree/-/espree-6.2.1.tgz#77fc72e1fd744a2052c20f38a5b575832e82734a" integrity sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw== dependencies: acorn "^7.1.1" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.1.0" espree@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/espree/-/espree-7.1.0.tgz#a9c7f18a752056735bf1ba14cb1b70adc3a5ce1c" integrity sha512-dcorZSyfmm4WTuTnE5Y7MEN1DyoPYy1ZR783QW1FJoenn7RailyWFsq/UL6ZAAA7uXurN9FIpYyUs3OfiIW+Qw== dependencies: acorn "^7.2.0" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.2.0" esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== esquery@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" integrity sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA== dependencies: estraverse "^4.0.0" esquery@^1.2.0: version "1.3.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.3.1.tgz#b78b5828aa8e214e29fb74c4d5b752e1c033da57" integrity sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ== dependencies: estraverse "^5.1.0" esrecurse@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf" integrity sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ== dependencies: estraverse "^4.1.0" esrecurse@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== dependencies: estraverse "^5.2.0" estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1: version "4.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== estraverse@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.1.0.tgz#374309d39fd935ae500e7b92e8a6b4c720e59642" integrity sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw== estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== esutils@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== etag@~1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc= events-to-array@^1.0.1: version "1.1.2" resolved "https://registry.yarnpkg.com/events-to-array/-/events-to-array-1.1.2.tgz#2d41f563e1fe400ed4962fe1a4d5c6a7539df7f6" integrity sha1-LUH1Y+H+QA7Uli/hpNXGp1Od9/Y= [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/events/-/events-1.1.1.tgz#9ebdb7635ad099c70dcc4c2a1f5004288e8bd924" integrity sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ= events@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/events/-/events-3.0.0.tgz#9a0a0dfaf62893d92b875b8f2698ca4114973e88" integrity sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA== events@^3.2.0: version "3.3.0" resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== execa@^4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2" integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A== dependencies: cross-spawn "^7.0.0" get-stream "^5.0.0" human-signals "^1.1.1" is-stream "^2.0.0" merge-stream "^2.0.0" npm-run-path "^4.0.0" onetime "^5.1.0" signal-exit "^3.0.2" strip-final-newline "^2.0.0" express@^4.16.4: version "4.18.2" resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59" integrity sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ== dependencies: accepts "~1.3.8" array-flatten "1.1.1" body-parser "1.20.1" content-disposition "0.5.4" content-type "~1.0.4" cookie "0.5.0" cookie-signature "1.0.6" debug "2.6.9" depd "2.0.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" finalhandler "1.2.0" fresh "0.5.2" http-errors "2.0.0" merge-descriptors "1.0.1" methods "~1.1.2" on-finished "2.4.1" parseurl "~1.3.3" path-to-regexp "0.1.7" proxy-addr "~2.0.7" qs "6.11.0" range-parser "~1.2.1" safe-buffer "5.2.1" send "0.18.0" serve-static "1.15.0" setprototypeof "1.2.0" statuses "2.0.1" type-is "~1.6.18" utils-merge "1.0.1" vary "~1.1.2" extend@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== external-editor@^3.0.3: version "3.1.0" resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== dependencies: chardet "^0.7.0" iconv-lite "^0.4.24" tmp "^0.0.33" extract-zip@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-2.0.1.tgz#663dca56fe46df890d5f131ef4a06d22bb8ba13a" integrity sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg== dependencies: debug "^4.1.1" get-stream "^5.1.0" yauzl "^2.10.0" optionalDependencies: "@types/yauzl" "^2.9.1" fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-glob@^3.1.1: version "3.2.4" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3" integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ== dependencies: "@nodelib/fs.stat" "^2.0.2" "@nodelib/fs.walk" "^1.2.3" glob-parent "^5.1.0" merge2 "^1.3.0" micromatch "^4.0.2" picomatch "^2.2.1" fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= fastest-levenshtein@^1.0.12: version "1.0.14" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.14.tgz#9054384e4b7a78c88d01a4432dc18871af0ac859" integrity sha512-tFfWHjnuUfKE186Tfgr+jtaFc0mZTApEgKDOeyN+FwOqRkO/zK/3h1AiRd8u8CY53owL3CUmGr/oI9p/RdyLTA== fastq@^1.6.0: version "1.8.0" resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481" integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q== dependencies: reusify "^1.0.4" fault@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fault/-/fault-2.0.0.tgz#ad2198a6e28e344dcda76a7b32406b1039f0b707" integrity sha512-JsDj9LFcoC+4ChII1QpXPA7YIaY8zmqPYw7h9j5n7St7a0BBKfNnwEBAUQRBx70o2q4rs+BeSNHk8Exm6xE7fQ== dependencies: format "^0.2.0" fd-slicer@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" integrity sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g== dependencies: pend "~1.2.0" figgy-pudding@^3.5.1: version "3.5.2" resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e" integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw== figures@^3.0.0, figures@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/figures/-/figures-3.2.0.tgz#625c18bd293c604dc4a8ddb2febf0c88341746af" integrity sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg== dependencies: escape-string-regexp "^1.0.5" file-entry-cache@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-5.0.1.tgz#ca0f6efa6dd3d561333fb14515065c2fafdf439c" integrity sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g== dependencies: flat-cache "^2.0.1" fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== dependencies: to-regex-range "^5.0.1" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32" integrity sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg== dependencies: debug "2.6.9" encodeurl "~1.0.2" escape-html "~1.0.3" on-finished "2.4.1" parseurl "~1.3.3" statuses "2.0.1" unpipe "~1.0.0" find-root@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng== find-up@^2.0.0, find-up@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= dependencies: locate-path "^2.0.0" find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" find-up@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== dependencies: locate-path "^5.0.0" path-exists "^4.0.0" flat-cache@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0" integrity sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA== dependencies: flatted "^2.0.0" rimraf "2.6.3" write "1.0.3" flatted@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== folder-hash@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/folder-hash/-/folder-hash-2.1.2.tgz#7109f9cd0cbca271936d1b5544b156d6571e6cfd" integrity sha512-PmMwEZyNN96EMshf7sek4OIB7ADNsHOJ7VIw7pO0PBI0BNfEsi7U8U56TBjjqqwQ0WuBv8se0HEfmbw5b/Rk+w== dependencies: debug "^3.1.0" graceful-fs "~4.1.11" minimatch "~3.0.4" form-data@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" form-data@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" format@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" integrity sha1-1hcBB+nv3E7TDJ3DkBbflCtctYs= [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow== [email protected]: version "0.5.2" resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac= fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" integrity sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ== dependencies: graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^2.0.0" fs-extra@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9" integrity sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw== dependencies: graceful-fs "^4.1.2" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== dependencies: graceful-fs "^4.2.0" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^9.0.1: version "9.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc" integrity sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ== dependencies: at-least-node "^1.0.0" graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^1.0.0" fs-minipass@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== dependencies: minipass "^3.0.0" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== functional-red-black-tree@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= get-func-name@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41" integrity sha1-6td0q+5y4gQJQzoGY2YCPdaIekE= get-intrinsic@^1.0.2: version "1.2.0" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.0.tgz#7ad1dc0535f3a2904bba075772763e5051f6d05f" integrity sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q== dependencies: function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.3" get-own-enumerable-property-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203" integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg== get-stdin@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-7.0.0.tgz#8d5de98f15171a125c5e516643c7a6d0ea8a96f6" integrity sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ== get-stdin@~9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-9.0.0.tgz#3983ff82e03d56f1b2ea0d3e60325f39d703a575" integrity sha512-dVKBjfWisLAicarI2Sf+JuBE/DghV4UzNAVe9yhEJuzeREd3JhOTE9cUaJTeSa77fsbQUK3pcOpJfM59+VKZaA== get-stream@^5.0.0, get-stream@^5.1.0: version "5.2.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: pump "^3.0.0" getos@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/getos/-/getos-3.2.1.tgz#0134d1f4e00eb46144c5a9c0ac4dc087cbb27dc5" integrity sha512-U56CfOK17OKgTVqozZjUKNdkfEv6jk5WISBJ8SHoagjE6L69zOwl3Z+O8myjY9MEW3i2HPWQBt/LTbCgcC973Q== dependencies: async "^3.2.0" glob-parent@^5.0.0, glob-parent@^5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" glob-to-regexp@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== glob@^7.0.0, glob@^7.0.5, glob@^7.1.3, glob@^7.1.6: version "7.2.0" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" glob@~8.0.3: version "8.0.3" resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" integrity sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^5.0.1" once "^1.3.0" global-agent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/global-agent/-/global-agent-3.0.0.tgz#ae7cd31bd3583b93c5a16437a1afe27cc33a1ab6" integrity sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q== dependencies: boolean "^3.0.1" es6-error "^4.1.1" matcher "^3.0.0" roarr "^2.15.3" semver "^7.3.2" serialize-error "^7.0.1" globals@^12.1.0: version "12.4.0" resolved "https://registry.yarnpkg.com/globals/-/globals-12.4.0.tgz#a18813576a41b00a24a97e7f815918c2e19925f8" integrity sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg== dependencies: type-fest "^0.8.1" globalthis@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.3.tgz#5852882a52b80dc301b0660273e1ed082f0b6ccf" integrity sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA== dependencies: define-properties "^1.1.3" globby@^11.0.0, globby@^11.0.1: version "11.0.1" resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357" integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ== dependencies: array-union "^2.1.0" dir-glob "^3.0.1" fast-glob "^3.1.1" ignore "^5.1.4" merge2 "^1.3.0" slash "^3.0.0" got@^11.8.5: version "11.8.5" resolved "https://registry.yarnpkg.com/got/-/got-11.8.5.tgz#ce77d045136de56e8f024bebb82ea349bc730046" integrity sha512-o0Je4NvQObAuZPHLFoRSkdG2lTgtcynqymzg2Vupdx6PorhaT5MCbIyXG6d4D94kk8ZG57QeosgdiqfJWhEhlQ== dependencies: "@sindresorhus/is" "^4.0.0" "@szmarczak/http-timer" "^4.0.5" "@types/cacheable-request" "^6.0.1" "@types/responselike" "^1.0.0" cacheable-lookup "^5.0.3" cacheable-request "^7.0.2" decompress-response "^6.0.0" http2-wrapper "^1.0.0-beta.5.2" lowercase-keys "^2.0.0" p-cancelable "^2.0.0" responselike "^2.0.0" graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.9: version "4.2.0" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.0.tgz#8d8fdc73977cb04104721cb53666c1ca64cd328b" integrity sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg== graceful-fs@^4.1.6, graceful-fs@^4.2.0: version "4.2.3" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ== graceful-fs@^4.2.4, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== graceful-fs@~4.1.11: version "4.1.15" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA== has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== has-flag@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-5.0.1.tgz#5483db2ae02a472d1d0691462fc587d1843cd940" integrity sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA== has-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= has-symbols@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== has-symbols@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== dependencies: function-bind "^1.1.1" hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw== http-cache-semantics@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3" integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ== dependencies: depd "2.0.0" inherits "2.0.4" setprototypeof "1.2.0" statuses "2.0.1" toidentifier "1.0.1" http2-wrapper@^1.0.0-beta.5.2: version "1.0.3" resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-1.0.3.tgz#b8f55e0c1f25d4ebd08b3b0c2c079f9590800b3d" integrity sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg== dependencies: quick-lru "^5.1.1" resolve-alpn "^1.0.0" human-signals@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== husky@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.1.tgz#511cb3e57de3e3190514ae49ed50f6bc3f50b3e9" integrity sha512-xs7/chUH/CKdOCs7Zy0Aev9e/dKOMZf3K1Az1nar3tzlv0jfqnYtu235bstsWTmXOR0EfINrPa97yy4Lz6RiKw== [email protected], iconv-lite@^0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" [email protected], ieee754@^1.1.4: version "1.1.13" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.13.tgz#ec168558e95aa181fd87d37f55c32bbcb6708b84" integrity sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg== ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== ignore@^4.0.6: version "4.0.6" resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.0.0, ignore@^5.1.1, ignore@^5.1.4: version "5.1.8" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== ignore@~5.2.4: version "5.2.4" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== import-fresh@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.1.0.tgz#6d33fa1dcef6df930fae003446f33415af905118" integrity sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-fresh@^3.1.0: version "3.2.1" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66" integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-local@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg== dependencies: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" import-meta-resolve@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-1.1.1.tgz#244fd542fd1fae73550d4f8b3cde3bba1d7b2b18" integrity sha512-JiTuIvVyPaUg11eTrNDx5bgQ/yMKMZffc7YSjvQeSMXy58DO2SQ8BtAf3xteZvmzvjYh14wnqNjL8XVeDy2o9A== dependencies: builtins "^4.0.0" imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= indent-string@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2, [email protected], inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@^1.3.5: version "1.3.7" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.7.tgz#a09363e1911972ea16d7a8851005d84cf09a9a84" integrity sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ== ini@~3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/ini/-/ini-3.0.1.tgz#c76ec81007875bc44d544ff7a11a55d12294102d" integrity sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ== inquirer@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.3.0.tgz#aa3e7cb0c18a410c3c16cdd2bc9dcbe83c4d333e" integrity sha512-K+LZp6L/6eE5swqIcVXrxl21aGDU4S50gKH0/d96OMQnSBCyGyZl/oZhbkVmdp5sBoINHd4xZvFSARh2dk6DWA== dependencies: ansi-escapes "^4.2.1" chalk "^4.1.0" cli-cursor "^3.1.0" cli-width "^3.0.0" external-editor "^3.0.3" figures "^3.0.0" lodash "^4.17.15" mute-stream "0.0.8" run-async "^2.4.0" rxjs "^6.6.0" string-width "^4.1.0" strip-ansi "^6.0.0" through "^2.3.6" interpret@^1.0.0: version "1.4.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== interpret@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== [email protected]: version "1.9.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== is-alphabetical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-2.0.0.tgz#ef6e2caea57c63450fffc7abb6cbdafc5eb96e96" integrity sha512-5OV8Toyq3oh4eq6sbWTYzlGdnMT/DPI5I0zxUBxjiigQsZycpkKF3kskkao3JyYGuYDHvhgJF+DrjMQp9SX86w== is-alphanumerical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-2.0.0.tgz#0fbfeb6a72d21d91143b3d182bf6cf5909ee66f6" integrity sha512-t+2GlJ+hO9yagJ+jU3+HSh80VKvz/3cG2cxbGGm4S0hjKuhWQXgPVUVOZz3tqZzMjhmphZ+1TIJTlRZRoe6GCQ== dependencies: is-alphabetical "^2.0.0" is-decimal "^2.0.0" is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== dependencies: binary-extensions "^2.0.0" is-buffer@^2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== is-callable@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== is-callable@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.0.tgz#83336560b54a38e35e3a2df7afd0454d691468bb" integrity sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw== is-core-module@^2.8.0: version "2.8.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.1.tgz#f59fdfca701d5879d0a6b100a40aa1560ce27211" integrity sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA== dependencies: has "^1.0.3" is-core-module@^2.9.0: version "2.9.0" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== dependencies: has "^1.0.3" is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= is-decimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.0.tgz#db1140337809fd043a056ae40a9bd1cdc563034c" integrity sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw== is-empty@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" integrity sha1-3pu1snhzigWgsJpX4ftNSjQan2s= is-extglob@^2.1.0, is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== is-fullwidth-code-point@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== is-glob@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= dependencies: is-extglob "^2.1.0" is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-hexadecimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.0.tgz#8e1ec9f48fe3eabd90161109856a23e0907a65d5" integrity sha512-vGOtYkiaxwIiR0+Ng/zNId+ZZehGfINwTzdrDqc6iubbnQWhnPuYymOzOKUDqa2cSl59yHnEh2h6MvRLQsyNug== is-interactive@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== is-obj@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= is-plain-obj@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.0.0.tgz#06c0999fd7574edf5a906ba5644ad0feb3a84d22" integrity sha512-NXRbBtUdBioI73y/HmOhogw/U5msYPC9DAtGkJXeFcFWSFZw0mCUsPxk/snTuJHzNKA8kLBK4rH97RMB1BfCXw== is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-plain-object@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-4.1.1.tgz#1a14d6452cbd50790edc7fdaa0aed5a40a35ebb5" integrity sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA== is-plain-object@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== is-regex@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= dependencies: has "^1.0.1" is-regex@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.0.tgz#ece38e389e490df0dc21caea2bd596f987f767ff" integrity sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw== dependencies: has-symbols "^1.0.1" is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= is-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== is-string@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== is-symbol@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== dependencies: has-symbols "^1.0.0" isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= jest-worker@^27.4.5: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== dependencies: "@types/node" "*" merge-stream "^2.0.0" supports-color "^8.0.0" [email protected]: version "0.15.0" resolved "https://registry.yarnpkg.com/jmespath/-/jmespath-0.15.0.tgz#a3f222a9aae9f966f5d27c796510e28091764217" integrity sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc= "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^3.13.1, js-yaml@^3.2.7: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== dependencies: argparse "^1.0.7" esprima "^4.0.0" js-yaml@^4.0.0, js-yaml@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== dependencies: argparse "^2.0.1" [email protected], json-buffer@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== json-parse-even-better-errors@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= json-stringify-safe@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== json5@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA== dependencies: minimist "^1.2.0" json5@^2.0.0, json5@^2.1.2: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== jsonc-parser@~3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= optionalDependencies: graceful-fs "^4.1.6" jsonfile@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.0.1.tgz#98966cba214378c8c84b82e085907b40bf614179" integrity sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg== dependencies: universalify "^1.0.0" optionalDependencies: graceful-fs "^4.1.6" jsonwebtoken@^9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz#d0faf9ba1cc3a56255fe49c0961a67e520c1926d" integrity sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw== dependencies: jws "^3.2.2" lodash "^4.17.21" ms "^2.1.1" semver "^7.3.8" jsx-ast-utils@^2.1.0: version "2.4.1" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz#1114a4c1209481db06c690c2b4f488cc665f657e" integrity sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w== dependencies: array-includes "^3.1.1" object.assign "^4.1.0" jwa@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a" integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA== dependencies: buffer-equal-constant-time "1.0.1" ecdsa-sig-formatter "1.0.11" safe-buffer "^5.0.1" jws@^3.2.2: version "3.2.2" resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304" integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA== dependencies: jwa "^1.4.1" safe-buffer "^5.0.1" keyv@^4.0.0: version "4.3.1" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.3.1.tgz#7970672f137d987945821b1a07b524ce5a4edd27" integrity sha512-nwP7AQOxFzELXsNq3zCx/oh81zu4DHWwCE6W9RaeHb7OHO0JpmKS8n801ovVQC7PTsZDWtPA5j1QY+/WWtARYg== dependencies: compress-brotli "^1.3.8" json-buffer "3.0.1" kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== klaw@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" integrity sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g== dependencies: graceful-fs "^4.1.9" kleur@^4.0.3: version "4.1.5" resolved "https://registry.yarnpkg.com/kleur/-/kleur-4.1.5.tgz#95106101795f7050c6c650f350c683febddb1780" integrity sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ== levn@^0.3.0, levn@~0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= dependencies: prelude-ls "~1.1.2" type-check "~0.3.2" levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== dependencies: prelude-ls "^1.2.1" type-check "~0.4.0" libnpmconfig@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/libnpmconfig/-/libnpmconfig-1.2.1.tgz#c0c2f793a74e67d4825e5039e7a02a0044dfcbc0" integrity sha512-9esX8rTQAHqarx6qeZqmGQKBNZR5OIbl/Ayr0qQDy3oXja2iFVQQI81R6GZ2a02bSNZ9p3YOGX1O6HHCb1X7kA== dependencies: figgy-pudding "^3.5.1" find-up "^3.0.0" ini "^1.3.5" lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= linkify-it@^3.0.1: version "3.0.3" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e" integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ== dependencies: uc.micro "^1.0.1" linkify-it@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-4.0.1.tgz#01f1d5e508190d06669982ba31a7d9f56a5751ec" integrity sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw== dependencies: uc.micro "^1.0.1" lint-staged@^10.2.11: version "10.2.11" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-10.2.11.tgz#713c80877f2dc8b609b05bc59020234e766c9720" integrity sha512-LRRrSogzbixYaZItE2APaS4l2eJMjjf5MbclRZpLJtcQJShcvUzKXsNeZgsLIZ0H0+fg2tL4B59fU9wHIHtFIA== dependencies: chalk "^4.0.0" cli-truncate "2.1.0" commander "^5.1.0" cosmiconfig "^6.0.0" debug "^4.1.1" dedent "^0.7.0" enquirer "^2.3.5" execa "^4.0.1" listr2 "^2.1.0" log-symbols "^4.0.0" micromatch "^4.0.2" normalize-path "^3.0.0" please-upgrade-node "^3.2.0" string-argv "0.3.1" stringify-object "^3.3.0" lint@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/lint/-/lint-1.1.2.tgz#35ed064f322547c331358d899868664968ba371f" integrity sha1-Ne0GTzIlR8MxNY2JmGhmSWi6Nx8= listr2@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/listr2/-/listr2-2.2.0.tgz#cb88631258abc578c7fb64e590fe5742f28e4aac" integrity sha512-Q8qbd7rgmEwDo1nSyHaWQeztfGsdL6rb4uh7BA+Q80AZiDET5rVntiU1+13mu2ZTDVaBVbvAD1Db11rnu3l9sg== dependencies: chalk "^4.0.0" cli-truncate "^2.1.0" figures "^3.2.0" indent-string "^4.0.0" log-update "^4.0.0" p-map "^4.0.0" rxjs "^6.5.5" through "^2.3.8" load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-2.0.0.tgz#7947e42149af80d696cbf797bcaabcfe1fe29ca8" integrity sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg= dependencies: graceful-fs "^4.1.2" parse-json "^2.2.0" pify "^2.0.0" strip-bom "^3.0.0" load-json-file@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-5.3.0.tgz#4d3c1e01fa1c03ea78a60ac7af932c9ce53403f3" integrity sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw== dependencies: graceful-fs "^4.1.15" parse-json "^4.0.0" pify "^4.0.1" strip-bom "^3.0.0" type-fest "^0.3.0" load-plugin@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/load-plugin/-/load-plugin-4.0.1.tgz#9a239b0337064c9b8aac82b0c9f89b067db487c5" integrity sha512-4kMi+mOSn/TR51pDo4tgxROHfBHXsrcyEYSGHcJ1o6TtRaP2PsRM5EwmYbj1uiLDvbfA/ohwuSWZJzqGiai8Dw== dependencies: import-meta-resolve "^1.0.0" libnpmconfig "^1.0.0" loader-runner@^4.2.0: version "4.3.0" resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== loader-utils@^1.0.2: version "1.4.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" integrity sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^1.0.1" loader-utils@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^2.1.2" locate-path@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" integrity sha1-K1aLJl7slExtnA3pw9u7ygNUzY4= dependencies: p-locate "^2.0.0" path-exists "^3.0.0" locate-path@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== dependencies: p-locate "^3.0.0" path-exists "^3.0.0" locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== dependencies: p-locate "^4.1.0" lodash.camelcase@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" integrity sha1-soqmKIorn8ZRA1x3EfZathkDMaY= lodash.flatten@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f" integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8= lodash.range@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/lodash.range/-/lodash.range-3.2.0.tgz#f461e588f66683f7eadeade513e38a69a565a15d" integrity sha1-9GHliPZmg/fq3q3lE+OKaaVloV0= lodash@^4.0.0, lodash@^4.17.11, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== dependencies: chalk "^2.0.1" log-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== dependencies: chalk "^2.4.2" log-symbols@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== dependencies: chalk "^4.0.0" log-update@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== dependencies: ansi-escapes "^4.3.0" cli-cursor "^3.1.0" slice-ansi "^4.0.0" wrap-ansi "^6.2.0" longest-streak@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-3.0.0.tgz#f127e2bded83caa6a35ac5f7a2f2b2f94b36f3dc" integrity sha512-XhUjWR5CFaQ03JOP+iSDS9koy8T5jfoImCZ4XprElw3BXsSk4MpVYOLw/6LTDKZhO13PlAXnB5gS4MHQTpkSOw== loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== dependencies: js-tokens "^3.0.0 || ^4.0.0" lowercase-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" make-error@^1.1.1: version "1.3.5" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== [email protected]: version "13.0.1" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-13.0.1.tgz#c6ecc431cacf1a5da531423fc6a42807814af430" integrity sha512-lTlxriVoy2criHP0JKRhO2VDG9c2ypWCsT237eDiLqi09rmbKoUetyGHq2uOIRoRS//kfoJckS0eUzzkDR+k2Q== dependencies: argparse "^2.0.1" entities "~3.0.1" linkify-it "^4.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdown-it@^12.0.0: version "12.3.2" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.3.2.tgz#bf92ac92283fe983fe4de8ff8abfb5ad72cd0c90" integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== dependencies: argparse "^2.0.1" entities "~2.1.0" linkify-it "^3.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdownlint-cli@^0.33.0: version "0.33.0" resolved "https://registry.yarnpkg.com/markdownlint-cli/-/markdownlint-cli-0.33.0.tgz#703af1234c32c309ab52fcd0e8bc797a34e2b096" integrity sha512-zMK1oHpjYkhjO+94+ngARiBBrRDEUMzooDHBAHtmEIJ9oYddd9l3chCReY2mPlecwH7gflQp1ApilTo+o0zopQ== dependencies: commander "~9.4.1" get-stdin "~9.0.0" glob "~8.0.3" ignore "~5.2.4" js-yaml "^4.1.0" jsonc-parser "~3.2.0" markdownlint "~0.27.0" minimatch "~5.1.2" run-con "~1.2.11" markdownlint@~0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.27.0.tgz#9dabf7710a4999e2835e3c68317f1acd0bc89049" integrity sha512-HtfVr/hzJJmE0C198F99JLaeada+646B5SaG2pVoEakLFI6iRGsvMqrnnrflq8hm1zQgwskEgqSnhDW11JBp0w== dependencies: markdown-it "13.0.1" matcher-collection@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/matcher-collection/-/matcher-collection-1.1.2.tgz#1076f506f10ca85897b53d14ef54f90a5c426838" integrity sha512-YQ/teqaOIIfUHedRam08PB3NK7Mjct6BvzRnJmpGDm8uFXpNr1sbY4yuflI5JcEs6COpYA0FpRQhSDBf1tT95g== dependencies: minimatch "^3.0.2" matcher@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca" integrity sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng== dependencies: escape-string-regexp "^4.0.0" mdast-comment-marker@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-comment-marker/-/mdast-comment-marker-1.1.1.tgz#9c9c18e1ed57feafc1965d92b028f37c3c8da70d" integrity sha512-TWZDaUtPLwKX1pzDIY48MkSUQRDwX/HqbTB4m3iYdL/zosi/Z6Xqfdv0C0hNVKvzrPjZENrpWDt4p4odeVO0Iw== mdast-util-from-markdown@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.0.tgz#c517313cd999ec2b8f6d447b438c5a9d500b89c9" integrity sha512-uj2G60sb7z1PNOeElFwCC9b/Se/lFXuLhVKFOAY2EHz/VvgbupTQRNXPoZl7rGpXYL6BNZgcgaybrlSWbo7n/g== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" mdast-util-to-string "^3.0.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" unist-util-stringify-position "^3.0.0" mdast-util-from-markdown@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.2.0.tgz#84df2924ccc6c995dec1e2368b2b208ad0a76268" integrity sha512-iZJyyvKD1+K7QX1b5jXdE7Sc5dtoTry1vzV28UZZe8Z1xVnB/czKntJ7ZAkG0tANqRnBF6p3p7GpU1y19DTf2Q== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" decode-named-character-reference "^1.0.0" mdast-util-to-string "^3.1.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-decode-string "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" unist-util-stringify-position "^3.0.0" uvu "^0.5.0" mdast-util-heading-style@^1.0.2: version "1.0.5" resolved "https://registry.yarnpkg.com/mdast-util-heading-style/-/mdast-util-heading-style-1.0.5.tgz#81b2e60d76754198687db0e8f044e42376db0426" integrity sha512-8zQkb3IUwiwOdUw6jIhnwM6DPyib+mgzQuHAe7j2Hy1rIarU4VUxe472bp9oktqULW3xqZE+Kz6OD4Gi7IA3vw== mdast-util-to-markdown@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-util-to-markdown/-/mdast-util-to-markdown-1.1.1.tgz#545ccc4dcc6672614b84fd1064482320dd689b12" integrity sha512-4puev/CxuxVdlsx5lVmuzgdqfjkkJJLS1Zm/MnejQ8I7BLeeBlbkwp6WOGJypEcN8g56LbVbhNmn84MvvcAvSQ== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" longest-streak "^3.0.0" mdast-util-to-string "^3.0.0" parse-entities "^3.0.0" zwitch "^2.0.0" mdast-util-to-string@^1.0.2: version "1.0.6" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-1.0.6.tgz#7d85421021343b33de1552fc71cb8e5b4ae7536d" integrity sha512-868pp48gUPmZIhfKrLbaDneuzGiw3OTDjHc5M1kAepR2CWBJ+HpEsm252K4aXdiP5coVZaJPOqGtVU6Po8xnXg== mdast-util-to-string@^3.0.0, mdast-util-to-string@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-3.1.0.tgz#56c506d065fbf769515235e577b5a261552d56e9" integrity sha512-n4Vypz/DZgwo0iMHLQL49dJzlp7YtAJP+N07MZHpjPf/5XJuHUWstviF4Mn2jEiR/GNmtnRRqnwsXExk3igfFA== mdurl@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= [email protected]: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g= memory-fs@^0.4.0: version "0.4.1" resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= dependencies: errno "^0.1.3" readable-stream "^2.0.1" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" integrity sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E= merge-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== merge2@^1.3.0: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== methods@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= micromark-core-commonmark@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-1.0.0.tgz#b767fa7687c205c224175bf067796360a3830350" integrity sha512-y9g7zymcKRBHM/aNBekstvs/Grpf+y4OEBULUTYvGZcusnp+JeOxmilJY4GMpo2/xY7iHQL9fjz5pD9pSAud9A== dependencies: micromark-factory-destination "^1.0.0" micromark-factory-label "^1.0.0" micromark-factory-space "^1.0.0" micromark-factory-title "^1.0.0" micromark-factory-whitespace "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-classify-character "^1.0.0" micromark-util-html-tag-name "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromark-factory-destination@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-destination/-/micromark-factory-destination-1.0.0.tgz#fef1cb59ad4997c496f887b6977aa3034a5a277e" integrity sha512-eUBA7Rs1/xtTVun9TmV3gjfPz2wEwgK5R5xcbIM5ZYAtvGF6JkyaDsj0agx8urXnO31tEO6Ug83iVH3tdedLnw== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-label@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz#b316ec479b474232973ff13b49b576f84a6f2cbb" integrity sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-space@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-space/-/micromark-factory-space-1.0.0.tgz#cebff49968f2b9616c0fcb239e96685cb9497633" integrity sha512-qUmqs4kj9a5yBnk3JMLyjtWYN6Mzfcx8uJfi5XAveBniDevmZasdGBba5b4QsvRcAkmvGo5ACmSUmyGiKTLZew== dependencies: micromark-util-character "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-title@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz#708f7a8044f34a898c0efdb4f55e4da66b537273" integrity sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-whitespace@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-whitespace/-/micromark-factory-whitespace-1.0.0.tgz#e991e043ad376c1ba52f4e49858ce0794678621c" integrity sha512-Qx7uEyahU1lt1RnsECBiuEbfr9INjQTGa6Err+gF3g0Tx4YEviPbqqGKNv/NrBaE7dVHdn1bVZKM/n5I/Bak7A== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-character@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/micromark-util-character/-/micromark-util-character-1.1.0.tgz#d97c54d5742a0d9611a68ca0cd4124331f264d86" integrity sha512-agJ5B3unGNJ9rJvADMJ5ZiYjBRyDpzKAOk01Kpi1TKhlT1APx3XZk6eN7RtSz1erbWHC2L8T3xLZ81wdtGRZzg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-chunked@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-chunked/-/micromark-util-chunked-1.0.0.tgz#5b40d83f3d53b84c4c6bce30ed4257e9a4c79d06" integrity sha512-5e8xTis5tEZKgesfbQMKRCyzvffRRUX+lK/y+DvsMFdabAicPkkZV6gO+FEWi9RfuKKoxxPwNL+dFF0SMImc1g== dependencies: micromark-util-symbol "^1.0.0" micromark-util-classify-character@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-classify-character/-/micromark-util-classify-character-1.0.0.tgz#cbd7b447cb79ee6997dd274a46fc4eb806460a20" integrity sha512-F8oW2KKrQRb3vS5ud5HIqBVkCqQi224Nm55o5wYLzY/9PwHGXC01tr3d7+TqHHz6zrKQ72Okwtvm/xQm6OVNZA== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-combine-extensions@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.0.0.tgz#91418e1e74fb893e3628b8d496085639124ff3d5" integrity sha512-J8H058vFBdo/6+AsjHp2NF7AJ02SZtWaVUjsayNFeAiydTxUwViQPxN0Hf8dp4FmCQi0UUFovFsEyRSUmFH3MA== dependencies: micromark-util-chunked "^1.0.0" micromark-util-types "^1.0.0" micromark-util-decode-numeric-character-reference@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.0.0.tgz#dcc85f13b5bd93ff8d2868c3dba28039d490b946" integrity sha512-OzO9AI5VUtrTD7KSdagf4MWgHMtET17Ua1fIpXTpuhclCqD8egFWo85GxSGvxgkGS74bEahvtM0WP0HjvV0e4w== dependencies: micromark-util-symbol "^1.0.0" micromark-util-decode-string@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/micromark-util-decode-string/-/micromark-util-decode-string-1.0.2.tgz#942252ab7a76dec2dbf089cc32505ee2bc3acf02" integrity sha512-DLT5Ho02qr6QWVNYbRZ3RYOSSWWFuH3tJexd3dgN1odEuPNxCngTCXJum7+ViRAd9BbdxCvMToPOD/IvVhzG6Q== dependencies: decode-named-character-reference "^1.0.0" micromark-util-character "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-encode@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-encode/-/micromark-util-encode-1.0.0.tgz#c409ecf751a28aa9564b599db35640fccec4c068" integrity sha512-cJpFVM768h6zkd8qJ1LNRrITfY4gwFt+tziPcIf71Ui8yFzY9wG3snZQqiWVq93PG4Sw6YOtcNiKJfVIs9qfGg== micromark-util-html-tag-name@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.0.0.tgz#75737e92fef50af0c6212bd309bc5cb8dbd489ed" integrity sha512-NenEKIshW2ZI/ERv9HtFNsrn3llSPZtY337LID/24WeLqMzeZhBEE6BQ0vS2ZBjshm5n40chKtJ3qjAbVV8S0g== micromark-util-normalize-identifier@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.0.0.tgz#4a3539cb8db954bbec5203952bfe8cedadae7828" integrity sha512-yg+zrL14bBTFrQ7n35CmByWUTFsgst5JhA4gJYoty4Dqzj4Z4Fr/DHekSS5aLfH9bdlfnSvKAWsAgJhIbogyBg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-resolve-all@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-resolve-all/-/micromark-util-resolve-all-1.0.0.tgz#a7c363f49a0162e931960c44f3127ab58f031d88" integrity sha512-CB/AGk98u50k42kvgaMM94wzBqozSzDDaonKU7P7jwQIuH2RU0TeBqGYJz2WY1UdihhjweivStrJ2JdkdEmcfw== dependencies: micromark-util-types "^1.0.0" micromark-util-sanitize-uri@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.0.0.tgz#27dc875397cd15102274c6c6da5585d34d4f12b2" integrity sha512-cCxvBKlmac4rxCGx6ejlIviRaMKZc0fWm5HdCHEeDWRSkn44l6NdYVRyU+0nT1XC72EQJMZV8IPHF+jTr56lAg== dependencies: micromark-util-character "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-subtokenize@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz#6f006fa719af92776c75a264daaede0fb3943c6a" integrity sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ== dependencies: micromark-util-chunked "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-symbol@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-symbol/-/micromark-util-symbol-1.0.0.tgz#91cdbcc9b2a827c0129a177d36241bcd3ccaa34d" integrity sha512-NZA01jHRNCt4KlOROn8/bGi6vvpEmlXld7EHcRH+aYWUfL3Wc8JLUNNlqUMKa0hhz6GrpUWsHtzPmKof57v0gQ== micromark-util-types@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-types/-/micromark-util-types-1.0.0.tgz#0ebdfaea3fa7c15fc82b1e06ea1ef0152d0fb2f0" integrity sha512-psf1WAaP1B77WpW4mBGDkTr+3RsPuDAgsvlP47GJzbH1jmjH8xjOx7Z6kp84L8oqHmy5pYO3Ev46odosZV+3AA== micromark@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/micromark/-/micromark-3.0.3.tgz#4c9f76fce8ba68eddf8730bb4fee2041d699d5b7" integrity sha512-fWuHx+JKV4zA8WfCFor2DWP9XmsZkIiyWRGofr7P7IGfpRIlb7/C5wwusGsNyr1D8HI5arghZDG1Ikc0FBwS5Q== dependencies: "@types/debug" "^4.0.0" debug "^4.0.0" micromark-core-commonmark "^1.0.0" micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-combine-extensions "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-sanitize-uri "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromatch@^4.0.0, micromatch@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259" integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q== dependencies: braces "^3.0.1" picomatch "^2.0.5" [email protected]: version "1.40.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32" integrity sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA== [email protected]: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== mime-types@^2.1.12, mime-types@^2.1.27, mime-types@~2.1.34: version "2.1.35" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== dependencies: mime-db "1.52.0" mime-types@~2.1.24: version "2.1.24" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81" integrity sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ== dependencies: mime-db "1.40.0" [email protected]: version "1.6.0" resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== mimic-fn@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== mimic-response@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== mimic-response@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.4: version "3.0.8" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.8.tgz#5e6a59bd11e2ab0de1cfb843eb2d82e546c321c1" integrity sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q== dependencies: brace-expansion "^1.1.7" minimatch@^5.0.1: version "5.1.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.1.tgz#6c9dffcf9927ff2a31e74b5af11adf8b9604b022" integrity sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g== dependencies: brace-expansion "^2.0.1" minimatch@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.2.tgz#0939d7d6f0898acbd1508abe534d1929368a8fff" integrity sha512-bNH9mmM9qsJ2X4r2Nat1B//1dJVcn3+iBLa3IgqJ7EbGaDNepL9QSHOxN4ng33s52VMMhhIfgCYDk3C4ZmlDAg== dependencies: brace-expansion "^2.0.1" minimist@^1.0.0, minimist@^1.2.5, minimist@^1.2.6, minimist@~1.2.0: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minimist@^1.2.0: version "1.2.7" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== minipass@^3.0.0: version "3.3.6" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw== dependencies: yallist "^4.0.0" minipass@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.1.tgz#2b9408c6e81bb8b338d600fb3685e375a370a057" integrity sha512-V9esFpNbK0arbN3fm2sxDKqMYgIp7XtVdE4Esj+PE4Qaaxdg1wIw48ITQIOn1sc8xXSmUviVL3cyjMqPlrVkiA== minizlib@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== dependencies: minipass "^3.0.0" yallist "^4.0.0" mkdirp@^0.5.1: version "0.5.5" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== dependencies: minimist "^1.2.5" mkdirp@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== mri@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= [email protected], ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== [email protected]: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== nan@nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac: version "2.15.0" resolved "https://codeload.github.com/nodejs/nan/tar.gz/16fa32231e2ccd89d2804b3f765319128b20c4ac" natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= [email protected]: version "0.6.3" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== neo-async@^2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-fetch@^2.6.1: version "2.6.8" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.8.tgz#a68d30b162bc1d8fd71a367e81b997e1f4d4937e" integrity sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg== dependencies: whatwg-url "^5.0.0" node-fetch@^2.6.7: version "2.6.7" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad" integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ== dependencies: whatwg-url "^5.0.0" node-releases@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503" integrity sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg== normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" resolve "^1.10.0" semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== normalize-url@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== npm-run-path@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: path-key "^3.0.0" null-loader@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-4.0.0.tgz#8e491b253cd87341d82c0e84b66980d806dfbd04" integrity sha512-vSoBF6M08/RHwc6r0gvB/xBJBtmbvvEkf6+IiadUCoNYchjxE8lwzCGFg0Qp2D25xPiJxUBh2iNWzlzGMILp7Q== dependencies: loader-utils "^2.0.0" schema-utils "^2.6.5" object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= object-inspect@^1.7.0: version "1.8.0" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.8.0.tgz#df807e5ecf53a609cc6bfe93eac3cc7be5b3a9d0" integrity sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA== object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g== object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object.assign@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== dependencies: define-properties "^1.1.2" function-bind "^1.1.1" has-symbols "^1.0.0" object-keys "^1.0.11" object.entries@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" has "^1.0.3" object.fromentries@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" integrity sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" object.values@^1.1.0, object.values@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.1.tgz#68a99ecde356b7e9295a3c5e0ce31dc8c953de5e" integrity sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" [email protected]: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== dependencies: ee-first "1.1.1" once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" onetime@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" integrity sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ= dependencies: mimic-fn "^1.0.0" onetime@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.0.tgz#fff0f3c91617fe62bb50189636e99ac8a6df7be5" integrity sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q== dependencies: mimic-fn "^2.1.0" optionator@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== dependencies: deep-is "~0.1.3" fast-levenshtein "~2.0.6" levn "~0.3.0" prelude-ls "~1.1.2" type-check "~0.3.2" word-wrap "~1.2.3" optionator@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== dependencies: deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" word-wrap "^1.2.3" ora@^3.4.0: version "3.4.0" resolved "https://registry.yarnpkg.com/ora/-/ora-3.4.0.tgz#bf0752491059a3ef3ed4c85097531de9fdbcd318" integrity sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg== dependencies: chalk "^2.4.2" cli-cursor "^2.1.0" cli-spinners "^2.0.0" log-symbols "^2.2.0" strip-ansi "^5.2.0" wcwidth "^1.0.1" ora@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.3.tgz#752a1b7b4be4825546a7a3d59256fa523b6b6d05" integrity sha512-fnDebVFyz309A73cqCipVL1fBZewq4vwgSHfxh43vVy31mbyoQ8sCH3Oeaog/owYOs/lLlGVPCISQonTneg6Pg== dependencies: chalk "^3.0.0" cli-cursor "^3.1.0" cli-spinners "^2.2.0" is-interactive "^1.0.0" log-symbols "^3.0.0" mute-stream "0.0.8" strip-ansi "^6.0.0" wcwidth "^1.0.1" os-tmpdir@^1.0.0, os-tmpdir@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= p-cancelable@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== p-limit@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8" integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q== dependencies: p-try "^1.0.0" p-limit@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2" integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ== dependencies: p-try "^2.0.0" p-limit@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" p-locate@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" integrity sha1-IKAQOyIqcMj9OcwuWAaA893l7EM= dependencies: p-limit "^1.1.0" p-locate@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== dependencies: p-limit "^2.0.0" p-locate@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== dependencies: p-limit "^2.2.0" p-map@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b" integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== dependencies: aggregate-error "^3.0.0" p-try@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3" integrity sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M= p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== parent-module@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== dependencies: callsites "^3.0.0" parse-entities@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-3.0.0.tgz#9ed6d6569b6cfc95ade058d683ddef239dad60dc" integrity sha512-AJlcIFDNPEP33KyJLguv0xJc83BNvjxwpuUIcetyXUsLpVXAUCePJ5kIoYtEN2R1ac0cYaRu/vk9dVFkewHQhQ== dependencies: character-entities "^2.0.0" character-entities-legacy "^2.0.0" character-reference-invalid "^2.0.0" is-alphanumerical "^2.0.0" is-decimal "^2.0.0" is-hexadecimal "^2.0.0" parse-gitignore@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/parse-gitignore/-/parse-gitignore-0.4.0.tgz#abf702e4b900524fff7902b683862857b63f93fe" integrity sha1-q/cC5LkAUk//eQK2g4YoV7Y/k/4= dependencies: array-unique "^0.3.2" is-glob "^3.1.0" parse-json@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= dependencies: error-ex "^1.2.0" parse-json@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= dependencies: error-ex "^1.3.1" json-parse-better-errors "^1.0.1" parse-json@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.0.0.tgz#73e5114c986d143efa3712d4ea24db9a4266f60f" integrity sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw== dependencies: "@babel/code-frame" "^7.0.0" error-ex "^1.3.1" json-parse-better-errors "^1.0.1" lines-and-columns "^1.1.6" parse-ms@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-key@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== path-parse@^1.0.6, path-parse@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== [email protected]: version "0.1.7" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w= path-type@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-2.0.0.tgz#f012ccb8415b7096fc2daa1054c3d72389594c73" integrity sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM= dependencies: pify "^2.0.0" path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== pathval@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pathval/-/pathval-1.1.1.tgz#8534e77a77ce7ac5a2512ea21e0fdb8fcf6c3d8d" integrity sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ== pend@~1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg== picocolors@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== picomatch@^2.0.4, picomatch@^2.0.5: version "2.0.7" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.0.7.tgz#514169d8c7cd0bdbeecc8a2609e34a7163de69f6" integrity sha512-oLHIdio3tZ0qH76NybpeneBhYVj0QFTfXEFTc/B3zKQspYfYYkWYgFsmzo+4kvId/bQRcNkVeguI3y+CD22BtA== picomatch@^2.2.1: version "2.2.2" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== picomatch@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== pify@^2.0.0: version "2.3.0" resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= pify@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== pkg-conf@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pkg-conf/-/pkg-conf-3.1.0.tgz#d9f9c75ea1bae0e77938cde045b276dac7cc69ae" integrity sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ== dependencies: find-up "^3.0.0" load-json-file "^5.2.0" pkg-config@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pkg-config/-/pkg-config-1.1.1.tgz#557ef22d73da3c8837107766c52eadabde298fe4" integrity sha1-VX7yLXPaPIg3EHdmxS6tq94pj+Q= dependencies: debug-log "^1.0.0" find-root "^1.0.0" xtend "^4.0.1" pkg-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-2.0.0.tgz#f6d5d1109e19d63edf428e0bd57e12777615334b" integrity sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s= dependencies: find-up "^2.1.0" pkg-dir@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== dependencies: find-up "^4.0.0" please-upgrade-node@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz#aeddd3f994c933e4ad98b99d9a556efa0e2fe942" integrity sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg== dependencies: semver-compare "^1.0.0" pluralize@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== pre-flight@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pre-flight/-/pre-flight-1.1.1.tgz#482fb1649fb400616a86b2706b11591f5cc8402d" integrity sha512-glqyc2Hh3K+sYeSsVs+HhjyUVf8j6xwuFej0yjYjRYfSnOK8P3Na9GznkoPn48fR+9kTOfkocYIWrtWktp4AqA== dependencies: colors "^1.1.2" commander "^2.9.0" semver "^5.1.0" prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== prelude-ls@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= pretty-ms@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.0.0.tgz#6133a8f55804b208e4728f6aa7bf01085e951e24" integrity sha512-94VRYjL9k33RzfKiGokPBPpsmloBYSf5Ri+Pq19zlsEcUKFob+admeXr5eFDRuPjFmEOcjJvPGdillYOJyvZ7Q== dependencies: parse-ms "^2.1.0" pretty-ms@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.1.0.tgz#b906bdd1ec9e9799995c372e2b1c34f073f95384" integrity sha512-4gaK1skD2gwscCfkswYQRmddUb2GJZtzDGRjHWadVHtK/DIKFufa12MvES6/xu1tVbUYeia5bmLcwJtZJQUqnw== dependencies: parse-ms "^2.1.0" process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== process@^0.11.10, process@~0.11.0: version "0.11.10" resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== progress@^2.0.0, progress@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== prop-types@^15.7.2: version "15.7.2" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== dependencies: loose-envify "^1.4.0" object-assign "^4.1.1" react-is "^16.8.1" proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= psl@^1.1.33: version "1.8.0" resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" integrity sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ== pump@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== dependencies: end-of-stream "^1.1.0" once "^1.3.1" [email protected]: version "1.3.2" resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" integrity sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0= punycode@^2.1.0, punycode@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== [email protected]: version "6.11.0" resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q== dependencies: side-channel "^1.0.4" [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA= quick-lru@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-5.1.1.tgz#366493e6b3e42a3a6885e2e99d18f80fb7a8c932" integrity sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA== ramda@^0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.27.0.tgz#915dc29865c0800bf3f69b8fd6c279898b59de43" integrity sha512-pVzZdDpWwWqEVVLshWUHjNwuVP7SfcmPraYuqocJp1yo2U1R7P+5QAfDhdItkuoGqIBnBYrtPp7rEPqDn9HlZA== randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== dependencies: safe-buffer "^5.1.0" range-parser@~1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== [email protected]: version "2.5.1" resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.1.tgz#fe1b1628b181b700215e5fd42389f98b71392857" integrity sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig== dependencies: bytes "3.1.2" http-errors "2.0.0" iconv-lite "0.4.24" unpipe "1.0.0" react-is@^16.8.1: version "16.8.6" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== read-pkg-up@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-2.0.0.tgz#6b72a8048984e0c41e79510fd5e9fa99b3b549be" integrity sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4= dependencies: find-up "^2.0.0" read-pkg "^2.0.0" read-pkg@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-2.0.0.tgz#8ef1c0623c6a6db0dc6713c4bfac46332b2368f8" integrity sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg= dependencies: load-json-file "^2.0.0" normalize-package-data "^2.3.2" path-type "^2.0.0" readable-stream@^2, readable-stream@^2.0.1, readable-stream@~2.3.6: version "2.3.6" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" isarray "~1.0.0" process-nextick-args "~2.0.0" safe-buffer "~5.1.1" string_decoder "~1.1.1" util-deprecate "~1.0.1" readable-stream@^3.0.2: version "3.6.0" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: inherits "^2.0.3" string_decoder "^1.1.1" util-deprecate "^1.0.1" readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== dependencies: picomatch "^2.2.1" rechoir@^0.6.2: version "0.6.2" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= dependencies: resolve "^1.1.6" rechoir@^0.7.0: version "0.7.1" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== dependencies: resolve "^1.9.0" regexpp@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-2.0.1.tgz#8d19d31cf632482b589049f8281f93dbcba4d07f" integrity sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw== regexpp@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.0.0.tgz#dd63982ee3300e67b41c1956f850aa680d9d330e" integrity sha512-Z+hNr7RAVWxznLPuA7DIh8UNX1j9CDrUQxskw9IrBE1Dxue2lyXT+shqEIeLUjrokxIP8CMy1WkjgG3rTsd5/g== regexpp@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== remark-cli@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-cli/-/remark-cli-10.0.0.tgz#3b0e20f2ad3909f35c7a6fb3f721c82f6ff5beac" integrity sha512-Yc5kLsJ5vgiQJl6xMLLJHqPac6OSAC5DOqKQrtmzJxSdJby2Jgr+OpIAkWQYwvbNHEspNagyoQnuwK2UCWg73g== dependencies: remark "^14.0.0" unified-args "^9.0.0" remark-lint-blockquote-indentation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-blockquote-indentation/-/remark-lint-blockquote-indentation-2.0.1.tgz#27347959acf42a6c3e401488d8210e973576b254" integrity sha512-uJ9az/Ms9AapnkWpLSCJfawBfnBI2Tn1yUsPNqIFv6YM98ymetItUMyP6ng9NFPqDvTQBbiarulkgoEo0wcafQ== dependencies: mdast-util-to-string "^1.0.2" pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-code-block-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-code-block-style/-/remark-lint-code-block-style-2.0.1.tgz#448b0f2660acfcdfff2138d125ff5b1c1279c0cb" integrity sha512-eRhmnColmSxJhO61GHZkvO67SpHDshVxs2j3+Zoc5Y1a4zQT2133ZAij04XKaBFfsVLjhbY/+YOWxgvtjx2nmA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-case@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-case/-/remark-lint-definition-case-2.0.1.tgz#10340eb2f87acff41140d52ad7e5b40b47e6690a" integrity sha512-M+XlThtQwEJLQnQb5Gi6xZdkw92rGp7m2ux58WMw/Qlcg02WgHR/O0OcHPe5VO5hMJrtI+cGG5T0svsCgRZd3w== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-spacing@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-spacing/-/remark-lint-definition-spacing-2.0.1.tgz#97f01bf9bf77a7bdf8013b124b7157dd90b07c64" integrity sha512-xK9DOQO5MudITD189VyUiMHBIKltW1oc55L7Fti3i9DedXoBG7Phm+V9Mm7IdWzCVkquZVgVk63xQdqzSQRrSQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-emphasis-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-emphasis-marker/-/remark-lint-emphasis-marker-2.0.1.tgz#1d5ca2070d4798d16c23120726158157796dc317" integrity sha512-7mpbAUrSnHiWRyGkbXRL5kfSKY9Cs8cdob7Fw+Z02/pufXMF4yRWaegJ5NTUu1RE+SKlF44wtWWjvcIoyY6/aw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-flag@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-flag/-/remark-lint-fenced-code-flag-2.0.1.tgz#2cb3ddb1157082c45760c7d01ca08e13376aaf62" integrity sha512-+COnWHlS/h02FMxoZWxNlZW3Y8M0cQQpmx3aNCbG7xkyMyCKsMLg9EmRvYHHIbxQCuF3JT0WWx5AySqlc7d+NA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-marker/-/remark-lint-fenced-code-marker-2.0.1.tgz#7bbeb0fb45b0818a3c8a2d232cf0c723ade58ecf" integrity sha512-lujpjm04enn3ma6lITlttadld6eQ1OWAEcT3qZzvFHp+zPraC0yr0eXlvtDN/0UH8mrln/QmGiZp3i8IdbucZg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-file-extension@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-file-extension/-/remark-lint-file-extension-1.0.3.tgz#a7fc78fbf041e513c618b2cca0f2160ee37daa13" integrity sha512-P5gzsxKmuAVPN7Kq1W0f8Ss0cFKfu+OlezYJWXf+5qOa+9Y5GqHEUOobPnsmNFZrVMiM7JoqJN2C9ZjrUx3N6Q== dependencies: unified-lint-rule "^1.0.0" remark-lint-final-definition@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/remark-lint-final-definition/-/remark-lint-final-definition-2.1.0.tgz#b6e654c01ebcb1afc936d7b9cd74db8ec273e0bb" integrity sha512-83K7n2icOHPfBzbR5Mr1o7cu8gOjD8FwJkFx/ly+rW+8SHfjCj4D3WOFGQ1xVdmHjfomBDXXDSNo2oiacADVXQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-hard-break-spaces@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-hard-break-spaces/-/remark-lint-hard-break-spaces-2.0.1.tgz#2149b55cda17604562d040c525a2a0d26aeb0f0f" integrity sha512-Qfn/BMQFamHhtbfLrL8Co/dbYJFLRL4PGVXZ5wumkUO5f9FkZC2RsV+MD9lisvGTkJK0ZEJrVVeaPbUIFM0OAw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-heading-increment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-increment/-/remark-lint-heading-increment-2.0.1.tgz#b578f251508a05d79bc2d1ae941e0620e23bf1d3" integrity sha512-bYDRmv/lk3nuWXs2VSD1B4FneGT6v7a74FuVmb305hyEMmFSnneJvVgnOJxyKlbNlz12pq1IQ6MhlJBda/SFtQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-heading-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-style/-/remark-lint-heading-style-2.0.1.tgz#8216fca67d97bbbeec8a19b6c71bfefc16549f72" integrity sha512-IrFLNs0M5Vbn9qg51AYhGUfzgLAcDOjh2hFGMz3mx664dV6zLcNZOPSdJBBJq3JQR4gKpoXcNwN1+FFaIATj+A== dependencies: mdast-util-heading-style "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-link-title-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-link-title-style/-/remark-lint-link-title-style-2.0.1.tgz#51a595c69fcfa73a245a030dfaa3504938a1173a" integrity sha512-+Q7Ew8qpOQzjqbDF6sUHmn9mKgje+m2Ho8Xz7cEnGIRaKJgtJzkn/dZqQM/az0gn3zaN6rOuwTwqw4EsT5EsIg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-list-item-content-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-content-indent/-/remark-lint-list-item-content-indent-2.0.1.tgz#96387459440dcd61e522ab02bff138b32bfaa63a" integrity sha512-OzUMqavxyptAdG7vWvBSMc9mLW9ZlTjbW4XGayzczd3KIr6Uwp3NEFXKx6MLtYIM/vwBqMrPQUrObOC7A2uBpQ== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-indent/-/remark-lint-list-item-indent-2.0.1.tgz#c6472514e17bc02136ca87936260407ada90bf8d" integrity sha512-4IKbA9GA14Q9PzKSQI6KEHU/UGO36CSQEjaDIhmb9UOhyhuzz4vWhnSIsxyI73n9nl9GGRAMNUSGzr4pQUFwTA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-spacing@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-list-item-spacing/-/remark-lint-list-item-spacing-3.0.0.tgz#14c18fe8c0f19231edb5cf94abda748bb773110b" integrity sha512-SRUVonwdN3GOSFb6oIYs4IfJxIVR+rD0nynkX66qEO49/qDDT1PPvkndis6Nyew5+t+2V/Db9vqllL6SWbnEtw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-maximum-heading-length@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-maximum-heading-length/-/remark-lint-maximum-heading-length-2.0.1.tgz#56f240707a75b59bce3384ccc9da94548affa98f" integrity sha512-1CjJ71YDqEpoOjUnc4wrwZV8ZGXWUIYRYeGoarAy3QKHepJL9M+zkdbOxZDfhc3tjVoDW/LWcgsW+DEpczgiMA== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-maximum-line-length@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/remark-lint-maximum-line-length/-/remark-lint-maximum-line-length-2.0.3.tgz#d0d15410637d61b031a83d7c78022ec46d6c858a" integrity sha512-zyWHBFh1oPAy+gkaVFXiTHYP2WwriIeBtaarDqkweytw0+qmuikjVMJTWbQ3+XfYBreD7KKDM9SI79nkp0/IZQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-auto-link-without-protocol@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-2.0.1.tgz#f75e5c24adb42385593e0d75ca39987edb70b6c4" integrity sha512-TFcXxzucsfBb/5uMqGF1rQA+WJJqm1ZlYQXyvJEXigEZ8EAxsxZGPb/gOQARHl/y0vymAuYxMTaChavPKaBqpQ== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-blockquote-without-marker@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-4.0.0.tgz#856fb64dd038fa8fc27928163caa24a30ff4d790" integrity sha512-Y59fMqdygRVFLk1gpx2Qhhaw5IKOR9T38Wf7pjR07bEFBGUNfcoNVIFMd1TCJfCPQxUyJzzSqfZz/KT7KdUuiQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-no-consecutive-blank-lines@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-consecutive-blank-lines/-/remark-lint-no-consecutive-blank-lines-3.0.0.tgz#c8fe11095b8f031a1406da273722bd4a9174bf41" integrity sha512-kmzLlOLrapBKEngwYFTdCZDmeOaze6adFPB7G0EdymD9V1mpAlnneINuOshRLEDKK5fAhXKiZXxdGIaMPkiXrA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-duplicate-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-duplicate-headings/-/remark-lint-no-duplicate-headings-2.0.1.tgz#4a4b70e029155ebcfc03d8b2358c427b69a87576" integrity sha512-F6AP0FJcHIlkmq0pHX0J5EGvLA9LfhuYTvnNO8y3kvflHeRjFkDyt2foz/taXR8OcLQR51n/jIJiwrrSMbiauw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-emphasis-as-heading@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-emphasis-as-heading/-/remark-lint-no-emphasis-as-heading-2.0.1.tgz#fcc064133fe00745943c334080fed822f72711ea" integrity sha512-z86+yWtVivtuGIxIC4g9RuATbgZgOgyLcnaleonJ7/HdGTYssjJNyqCJweaWSLoaI0akBQdDwmtJahW5iuX3/g== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-file-name-articles@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-articles/-/remark-lint-no-file-name-articles-1.0.3.tgz#c712d06a24e24b0c4c3666cf3084a0052a2c2c17" integrity sha512-YZDJDKUWZEmhrO6tHB0u0K0K2qJKxyg/kryr14OaRMvWLS62RgMn97sXPZ38XOSN7mOcCnl0k7/bClghJXx0sg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-consecutive-dashes@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-consecutive-dashes/-/remark-lint-no-file-name-consecutive-dashes-1.0.3.tgz#6a96ddf60e18dcdb004533733f3ccbfd8ab076ae" integrity sha512-7f4vyXn/ca5lAguWWC3eu5hi8oZ7etX7aQlnTSgQZeslnJCbVJm6V6prFJKAzrqbBzMicUXr5pZLBDoXyTvHHw== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-irregular-characters@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-irregular-characters/-/remark-lint-no-file-name-irregular-characters-1.0.3.tgz#6dcd8b51e00e10094585918cb8e7fc999df776c3" integrity sha512-b4xIy1Yi8qZpM2vnMN+6gEujagPGxUBAs1judv6xJQngkl5d5zT8VQZsYsTGHku4NWHjjh3b7vK5mr0/yp4JSg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-mixed-case@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-mixed-case/-/remark-lint-no-file-name-mixed-case-1.0.3.tgz#0ebe5eedd0191507d27ad6ac5eed1778cb33c2de" integrity sha512-d7rJ4c8CzDbEbGafw2lllOY8k7pvnsO77t8cV4PHFylwQ3hmCdTHLuDvK87G3DaWCeKclp0PMyamfOgJWKMkPA== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-outer-dashes@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-outer-dashes/-/remark-lint-no-file-name-outer-dashes-1.0.4.tgz#c6e22a5cc64df4e12fc31712a927e8039854a666" integrity sha512-+bZvvme2Bm3Vp5L2iKuvGHYVmHKrTkkRt8JqJPGepuhvBvT4Q7+CgfKyMtC/hIjyl+IcuJQ2H0qPRzdicjy1wQ== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-heading-punctuation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-heading-punctuation/-/remark-lint-no-heading-punctuation-2.0.1.tgz#face59f9a95c8aa278a8ee0c728bc44cd53ea9ed" integrity sha512-lY/eF6GbMeGu4cSuxfGHyvaQQBIq/6T/o+HvAR5UfxSTxmxZFwbZneAI2lbeR1zPcqOU87NsZ5ZZzWVwdLpPBw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-inline-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-inline-padding/-/remark-lint-no-inline-padding-3.0.0.tgz#14c2722bcddc648297a54298107a922171faf6eb" integrity sha512-3s9uW3Yux9RFC0xV81MQX3bsYs+UY7nPnRuMxeIxgcVwxQ4E/mTJd9QjXUwBhU9kdPtJ5AalngdmOW2Tgar8Cg== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-literal-urls@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-literal-urls/-/remark-lint-no-literal-urls-2.0.1.tgz#731908f9866c1880e6024dcee1269fb0f40335d6" integrity sha512-IDdKtWOMuKVQIlb1CnsgBoyoTcXU3LppelDFAIZePbRPySVHklTtuK57kacgU5grc7gPM04bZV96eliGrRU7Iw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-multiple-toplevel-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-multiple-toplevel-headings/-/remark-lint-no-multiple-toplevel-headings-2.0.1.tgz#3ff2b505adf720f4ff2ad2b1021f8cfd50ad8635" integrity sha512-VKSItR6c+u3OsE5pUiSmNusERNyQS9Nnji26ezoQ1uvy06k3RypIjmzQqJ/hCkSiF+hoyC3ibtrrGT8gorzCmQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-shell-dollars@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/remark-lint-no-shell-dollars/-/remark-lint-no-shell-dollars-2.0.2.tgz#b2c6c3ed95e5615f8e5f031c7d271a18dc17618e" integrity sha512-zhkHZOuyaD3r/TUUkkVqW0OxsR9fnSrAnHIF63nfJoAAUezPOu8D1NBsni6rX8H2DqGbPYkoeWrNsTwiKP0yow== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-image@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-image/-/remark-lint-no-shortcut-reference-image-2.0.1.tgz#d174d12a57e8307caf6232f61a795bc1d64afeaa" integrity sha512-2jcZBdnN6ecP7u87gkOVFrvICLXIU5OsdWbo160FvS/2v3qqqwF2e/n/e7D9Jd+KTq1mR1gEVVuTqkWWuh3cig== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-link@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-link/-/remark-lint-no-shortcut-reference-link-2.0.1.tgz#8f963f81036e45cfb7061b3639e9c6952308bc94" integrity sha512-pTZbslG412rrwwGQkIboA8wpBvcjmGFmvugIA+UQR+GfFysKtJ5OZMPGJ98/9CYWjw9Z5m0/EktplZ5TjFjqwA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-table-indentation@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-table-indentation/-/remark-lint-no-table-indentation-3.0.0.tgz#f3c3fc24375069ec8e510f43050600fb22436731" integrity sha512-+l7GovI6T+3LhnTtz/SmSRyOb6Fxy6tmaObKHrwb/GAebI/4MhFS1LVo3vbiP/RpPYtyQoFbbuXI55hqBG4ibQ== dependencies: unified-lint-rule "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-ordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-style/-/remark-lint-ordered-list-marker-style-2.0.1.tgz#183c31967e6f2ae8ef00effad03633f7fd00ffaa" integrity sha512-Cnpw1Dn9CHn+wBjlyf4qhPciiJroFOEGmyfX008sQ8uGoPZsoBVIJx76usnHklojSONbpjEDcJCjnOvfAcWW1A== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-ordered-list-marker-value@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-value/-/remark-lint-ordered-list-marker-value-2.0.1.tgz#0de343de2efb41f01eae9f0f7e7d30fe43db5595" integrity sha512-blt9rS7OKxZ2NW8tqojELeyNEwPhhTJGVa+YpUkdEH+KnrdcD7Nzhnj6zfLWOx6jFNZk3jpq5nvLFAPteHaNKg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-rule-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-rule-style/-/remark-lint-rule-style-2.0.1.tgz#f59bd82e75d3eaabd0eee1c8c0f5513372eb553c" integrity sha512-hz4Ff9UdlYmtO6Czz99WJavCjqCer7Cav4VopXt+yVIikObw96G5bAuLYcVS7hvMUGqC9ZuM02/Y/iq9n8pkAg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-strong-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-strong-marker/-/remark-lint-strong-marker-2.0.1.tgz#1ad8f190c6ac0f8138b638965ccf3bcd18f6d4e4" integrity sha512-8X2IsW1jZ5FmW9PLfQjkL0OVy/J3xdXLcZrG1GTeQKQ91BrPFyEZqUM2oM6Y4S6LGtxWer+neZkPZNroZoRPBQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-cell-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-cell-padding/-/remark-lint-table-cell-padding-3.0.0.tgz#a769ba1999984ff5f90294fb6ccb8aead7e8a12f" integrity sha512-sEKrbyFZPZpxI39R8/r+CwUrin9YtyRwVn0SQkNQEZWZcIpylK+bvoKIldvLIXQPob+ZxklL0GPVRzotQMwuWQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipe-alignment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-table-pipe-alignment/-/remark-lint-table-pipe-alignment-2.0.1.tgz#12b7e4c54473d69c9866cb33439c718d09cffcc5" integrity sha512-O89U7bp0ja6uQkT2uQrNB76GaPvFabrHiUGhqEUnld21yEdyj7rgS57kn84lZNSuuvN1Oor6bDyCwWQGzzpoOQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-pipes/-/remark-lint-table-pipes-3.0.0.tgz#b30b055d594cae782667eec91c6c5b35928ab259" integrity sha512-QPokSazEdl0Y8ayUV9UB0Ggn3Jos/RAQwIo0z1KDGnJlGDiF80Jc6iU9RgDNUOjlpQffSLIfSVxH5VVYF/K3uQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-unordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-unordered-list-marker-style/-/remark-lint-unordered-list-marker-style-2.0.1.tgz#e64692aa9594dbe7e945ae76ab2218949cd92477" integrity sha512-8KIDJNDtgbymEvl3LkrXgdxPMTOndcux3BHhNGB2lU4UnxSpYeHsxcDgirbgU6dqCAfQfvMjPvfYk19QTF9WZA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/remark-lint/-/remark-lint-8.0.0.tgz#6e40894f4a39eaea31fc4dd45abfaba948bf9a09" integrity sha512-ESI8qJQ/TIRjABDnqoFsTiZntu+FRifZ5fJ77yX63eIDijl/arvmDvT+tAf75/Nm5BFL4R2JFUtkHRGVjzYUsg== dependencies: remark-message-control "^6.0.0" remark-message-control@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/remark-message-control/-/remark-message-control-6.0.0.tgz#955b054b38c197c9f2e35b1d88a4912949db7fc5" integrity sha512-k9bt7BYc3G7YBdmeAhvd3VavrPa/XlKWR3CyHjr4sLO9xJyly8WHHT3Sp+8HPR8lEUv+/sZaffL7IjMLV0f6BA== dependencies: mdast-comment-marker "^1.0.0" unified-message-control "^3.0.0" remark-parse@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-parse/-/remark-parse-10.0.0.tgz#65e2b2b34d8581d36b97f12a2926bb2126961cb4" integrity sha512-07ei47p2Xl7Bqbn9H2VYQYirnAFJPwdMuypdozWsSbnmrkgA2e2sZLZdnDNrrsxR4onmIzH/J6KXqKxCuqHtPQ== dependencies: "@types/mdast" "^3.0.0" mdast-util-from-markdown "^1.0.0" unified "^10.0.0" remark-preset-lint-markdown-style-guide@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-preset-lint-markdown-style-guide/-/remark-preset-lint-markdown-style-guide-4.0.0.tgz#976b6ffd7f37aa90868e081a69241fcde3a297d4" integrity sha512-gczDlfZ28Fz0IN/oddy0AH4CiTu9S8d3pJWUsrnwFiafjhJjPGobGE1OD3bksi53md1Bp4K0fzo99YYfvB4Sjw== dependencies: remark-lint "^8.0.0" remark-lint-blockquote-indentation "^2.0.0" remark-lint-code-block-style "^2.0.0" remark-lint-definition-case "^2.0.0" remark-lint-definition-spacing "^2.0.0" remark-lint-emphasis-marker "^2.0.0" remark-lint-fenced-code-flag "^2.0.0" remark-lint-fenced-code-marker "^2.0.0" remark-lint-file-extension "^1.0.0" remark-lint-final-definition "^2.0.0" remark-lint-hard-break-spaces "^2.0.0" remark-lint-heading-increment "^2.0.0" remark-lint-heading-style "^2.0.0" remark-lint-link-title-style "^2.0.0" remark-lint-list-item-content-indent "^2.0.0" remark-lint-list-item-indent "^2.0.0" remark-lint-list-item-spacing "^3.0.0" remark-lint-maximum-heading-length "^2.0.0" remark-lint-maximum-line-length "^2.0.0" remark-lint-no-auto-link-without-protocol "^2.0.0" remark-lint-no-blockquote-without-marker "^4.0.0" remark-lint-no-consecutive-blank-lines "^3.0.0" remark-lint-no-duplicate-headings "^2.0.0" remark-lint-no-emphasis-as-heading "^2.0.0" remark-lint-no-file-name-articles "^1.0.0" remark-lint-no-file-name-consecutive-dashes "^1.0.0" remark-lint-no-file-name-irregular-characters "^1.0.0" remark-lint-no-file-name-mixed-case "^1.0.0" remark-lint-no-file-name-outer-dashes "^1.0.0" remark-lint-no-heading-punctuation "^2.0.0" remark-lint-no-inline-padding "^3.0.0" remark-lint-no-literal-urls "^2.0.0" remark-lint-no-multiple-toplevel-headings "^2.0.0" remark-lint-no-shell-dollars "^2.0.0" remark-lint-no-shortcut-reference-image "^2.0.0" remark-lint-no-shortcut-reference-link "^2.0.0" remark-lint-no-table-indentation "^3.0.0" remark-lint-ordered-list-marker-style "^2.0.0" remark-lint-ordered-list-marker-value "^2.0.0" remark-lint-rule-style "^2.0.0" remark-lint-strong-marker "^2.0.0" remark-lint-table-cell-padding "^3.0.0" remark-lint-table-pipe-alignment "^2.0.0" remark-lint-table-pipes "^3.0.0" remark-lint-unordered-list-marker-style "^2.0.0" remark-stringify@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-10.0.0.tgz#7f23659d92b2d5da489e3c858656d7bbe045f161" integrity sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA== dependencies: "@types/mdast" "^3.0.0" mdast-util-to-markdown "^1.0.0" unified "^10.0.0" remark@^14.0.0: version "14.0.1" resolved "https://registry.yarnpkg.com/remark/-/remark-14.0.1.tgz#a97280d4f2a3010a7d81e6c292a310dcd5554d80" integrity sha512-7zLG3u8EUjOGuaAS9gUNJPD2j+SqDqAFHv2g6WMpE5CU9rZ6e3IKDM12KHZ3x+YNje+NMAuN55yx8S5msGSx7Q== dependencies: "@types/mdast" "^3.0.0" remark-parse "^10.0.0" remark-stringify "^10.0.0" unified "^10.0.0" repeat-string@^1.0.0: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= requireindex@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.1.0.tgz#e5404b81557ef75db6e49c5a72004893fe03e162" integrity sha1-5UBLgVV+91225JxacgBIk/4D4WI= resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" integrity sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g== resolve-cwd@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== dependencies: resolve-from "^5.0.0" resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== resolve-from@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== resolve@^1.1.6: version "1.21.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.21.0.tgz#b51adc97f3472e6a5cf4444d34bc9d6b9037591f" integrity sha512-3wCbTpk5WJlyE4mSOtDLhqQmGFi0/TD9VPwmiolnk8U0wRgMEktqCXd3vy5buTO3tljvalNvKrjHEfrd2WpEKA== dependencies: is-core-module "^2.8.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" resolve@^1.10.0: version "1.11.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e" integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw== dependencies: path-parse "^1.0.6" resolve@^1.10.1, resolve@^1.11.0, resolve@^1.13.1, resolve@^1.17.0: version "1.17.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== dependencies: path-parse "^1.0.6" resolve@^1.9.0: version "1.22.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177" integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw== dependencies: is-core-module "^2.9.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" responselike@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/responselike/-/responselike-2.0.0.tgz#26391bcc3174f750f9a79eacc40a12a5c42d7723" integrity sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw== dependencies: lowercase-keys "^2.0.0" restore-cursor@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" integrity sha1-n37ih/gv0ybU/RYpI9YhKe7g368= dependencies: onetime "^2.0.0" signal-exit "^3.0.2" restore-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== dependencies: onetime "^5.1.0" signal-exit "^3.0.2" reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== [email protected]: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== dependencies: glob "^7.1.3" rimraf@~2.2.6: version "2.2.8" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.8.tgz#e439be2aaee327321952730f99a8929e4fc50582" integrity sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI= roarr@^2.15.3: version "2.15.4" resolved "https://registry.yarnpkg.com/roarr/-/roarr-2.15.4.tgz#f5fe795b7b838ccfe35dc608e0282b9eba2e7afd" integrity sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A== dependencies: boolean "^3.0.1" detect-node "^2.0.4" globalthis "^1.0.1" json-stringify-safe "^5.0.1" semver-compare "^1.0.0" sprintf-js "^1.1.2" run-async@^2.4.0: version "2.4.1" resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" integrity sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ== run-con@~1.2.11: version "1.2.11" resolved "https://registry.yarnpkg.com/run-con/-/run-con-1.2.11.tgz#0014ed430bad034a60568dfe7de2235f32e3f3c4" integrity sha512-NEMGsUT+cglWkzEr4IFK21P4Jca45HqiAbIIZIBdX5+UZTB24Mb/21iNGgz9xZa8tL6vbW7CXmq7MFN42+VjNQ== dependencies: deep-extend "^0.6.0" ini "~3.0.0" minimist "^1.2.6" strip-json-comments "~3.1.1" run-parallel@^1.1.2, run-parallel@^1.1.9: version "1.1.9" resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679" integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q== rxjs@^6.5.5, rxjs@^6.6.0: version "6.6.0" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.6.0.tgz#af2901eedf02e3a83ffa7f886240ff9018bbec84" integrity sha512-3HMA8z/Oz61DUHe+SdOiQyzIf4tOx5oQHmMir7IZEu6TMqCLHT4LRcmNaUS0NwOz8VLvmmBduMsoaUvMaIiqzg== dependencies: tslib "^1.9.0" sade@^1.7.3: version "1.8.1" resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701" integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A== dependencies: mri "^1.1.0" [email protected], safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== "safer-buffer@>= 2.1.2 < 3": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== [email protected]: version "1.2.1" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.1.tgz#7b8e656190b228e81a66aea748480d828cd2d37a" integrity sha1-e45lYZCyKOgaZq6nSEgNgozS03o= sax@>=0.6.0: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== schema-utils@^2.6.5: version "2.7.0" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.7.0.tgz#17151f76d8eae67fbbf77960c33c676ad9f4efc7" integrity sha512-0ilKFI6QQF5nxDZLFn2dMjvc4hjg/Wkg7rHd3jK6/A4a1Hl9VFdQWvgB1UMGoU94pad1P/8N7fMcEnLnSiju8A== dependencies: "@types/json-schema" "^7.0.4" ajv "^6.12.2" ajv-keywords "^3.4.1" schema-utils@^3.1.0, schema-utils@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-3.1.1.tgz#bc74c4b6b6995c1d88f76a8b77bea7219e0c8281" integrity sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw== dependencies: "@types/json-schema" "^7.0.8" ajv "^6.12.5" ajv-keywords "^3.5.2" semver-compare@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= "semver@2 || 3 || 4 || 5", semver@^5.6.0: version "5.7.0" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b" integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA== semver@^5.1.0, semver@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db" integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A== semver@^6.1.0, semver@^6.1.2, semver@^6.2.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== semver@^7.0.0: version "7.3.5" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7" integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== dependencies: lru-cache "^6.0.0" semver@^7.2.1, semver@^7.3.2: version "7.3.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938" integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ== semver@^7.3.5, semver@^7.3.8: version "7.3.8" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== dependencies: lru-cache "^6.0.0" [email protected]: version "0.18.0" resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be" integrity sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg== dependencies: debug "2.6.9" depd "2.0.0" destroy "1.2.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" fresh "0.5.2" http-errors "2.0.0" mime "1.6.0" ms "2.1.3" on-finished "2.4.1" range-parser "~1.2.1" statuses "2.0.1" serialize-error@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/serialize-error/-/serialize-error-7.0.1.tgz#f1360b0447f61ffb483ec4157c737fab7d778e18" integrity sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw== dependencies: type-fest "^0.13.1" serialize-javascript@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== dependencies: randombytes "^2.1.0" [email protected]: version "1.15.0" resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.15.0.tgz#faaef08cffe0a1a62f60cad0c4e513cff0ac9540" integrity sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g== dependencies: encodeurl "~1.0.2" escape-html "~1.0.3" parseurl "~1.3.3" send "0.18.0" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== shallow-clone@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== dependencies: kind-of "^6.0.2" shebang-command@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= dependencies: shebang-regex "^1.0.0" shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== dependencies: shebang-regex "^3.0.0" shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= shebang-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== shelljs@^0.8.1: version "0.8.5" resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.8.5.tgz#de055408d8361bed66c669d2f000538ced8ee20c" integrity sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow== dependencies: glob "^7.0.0" interpret "^1.0.0" rechoir "^0.6.2" shx@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/shx/-/shx-0.3.2.tgz#40501ce14eb5e0cbcac7ddbd4b325563aad8c123" integrity sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA== dependencies: es6-object-assign "^1.0.3" minimist "^1.2.0" shelljs "^0.8.1" side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== dependencies: call-bind "^1.0.0" get-intrinsic "^1.0.2" object-inspect "^1.9.0" signal-exit@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== simple-git@^3.5.0: version "3.16.0" resolved "https://registry.yarnpkg.com/simple-git/-/simple-git-3.16.0.tgz#421773e24680f5716999cc4a1d60127b4b6a9dec" integrity sha512-zuWYsOLEhbJRWVxpjdiXl6eyAyGo/KzVW+KFhhw9MqEEJttcq+32jTWSGyxTdf9e/YCohxRE+9xpWFj9FdiJNw== dependencies: "@kwsites/file-exists" "^1.1.1" "@kwsites/promise-deferred" "^1.1.1" debug "^4.3.4" slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== slice-ansi@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-2.1.0.tgz#cacd7693461a637a5788d92a7dd4fba068e81636" integrity sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ== dependencies: ansi-styles "^3.2.0" astral-regex "^1.0.0" is-fullwidth-code-point "^2.0.0" slice-ansi@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" slice-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" sliced@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/sliced/-/sliced-1.0.1.tgz#0b3a662b5d04c3177b1926bea82b03f837a2ef41" integrity sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E= source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map@^0.6.0: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== spdx-correct@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== spdx-expression-parse@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: version "3.0.4" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz#75ecd1a88de8c184ef015eafb51b5b48bfd11bb1" integrity sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA== sprintf-js@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.2.tgz#da1765262bf8c0f571749f2ad6c26300207ae673" integrity sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug== sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= standard-engine@^12.0.0: version "12.1.0" resolved "https://registry.yarnpkg.com/standard-engine/-/standard-engine-12.1.0.tgz#b13dbae583de54c06805207b991ef48a582c0e62" integrity sha512-DVJnWM1CGkag4ucFLGdiYWa5/kJURPONmMmk17p8FT5NE4UnPZB1vxWnXnRo2sPSL78pWJG8xEM+1Tu19z0deg== dependencies: deglob "^4.0.1" get-stdin "^7.0.0" minimist "^1.2.5" pkg-conf "^3.1.0" standard-markdown@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/standard-markdown/-/standard-markdown-6.0.0.tgz#bb7519a86275900eaa7a951d98937723c7010ed6" integrity sha512-9lQs4ZfGukyalFVputnN4IxfbMIAECjf+BqC4gvY8eBUvYcotYIWj4MZyMiXBkN/OJwmMi5jVSnzIexKZQqQYA== dependencies: commander "^4.1.0" globby "^11.0.0" lodash.flatten "^4.4.0" lodash.range "^3.2.0" ora "^4.0.3" standard "^14.3.1" standard@^14.3.1: version "14.3.4" resolved "https://registry.yarnpkg.com/standard/-/standard-14.3.4.tgz#748e80e8cd7b535844a85a12f337755a7e3a0f6e" integrity sha512-+lpOkFssMkljJ6eaILmqxHQ2n4csuEABmcubLTb9almFi1ElDzXb1819fjf/5ygSyePCq4kU2wMdb2fBfb9P9Q== dependencies: eslint "~6.8.0" eslint-config-standard "14.1.1" eslint-config-standard-jsx "8.1.0" eslint-plugin-import "~2.18.0" eslint-plugin-node "~10.0.0" eslint-plugin-promise "~4.2.1" eslint-plugin-react "~7.14.2" eslint-plugin-standard "~4.0.0" standard-engine "^12.0.0" [email protected]: version "2.0.1" resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== stream-chain@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/stream-chain/-/stream-chain-2.2.3.tgz#44cfa21ab673e53a3f1691b3d1665c3aceb1983b" integrity sha512-w+WgmCZ6BItPAD3/4HD1eDiDHRLhjSSyIV+F0kcmmRyz8Uv9hvQF22KyaiAUmOlmX3pJ6F95h+C191UbS8Oe/g== stream-json@^1.7.1: version "1.7.1" resolved "https://registry.yarnpkg.com/stream-json/-/stream-json-1.7.1.tgz#ec7e414c2eba456c89a4b4e5223794eabc3860c4" integrity sha512-I7g0IDqvdJXbJ279/D3ZoTx0VMhmKnEF7u38CffeWdF8bfpMPsLo+5fWnkNjO2GU/JjWaRjdH+zmH03q+XGXFw== dependencies: stream-chain "^2.2.3" [email protected]: version "0.3.1" resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== string-width@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== dependencies: emoji-regex "^7.0.1" is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" string-width@^4.1.0, string-width@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== dependencies: emoji-regex "^8.0.0" is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" string-width@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.0.0.tgz#19191f152f937b96f4ec54ba0986a5656660c5a2" integrity sha512-zwXcRmLUdiWhMPrHz6EXITuyTgcEnUqDzspTkCLhQovxywWz6NP9VHgqfVg20V/1mUg0B95AKbXxNT+ALRmqCw== dependencies: emoji-regex "^9.2.2" is-fullwidth-code-point "^4.0.0" strip-ansi "^7.0.0" string.prototype.trimend@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz#85812a6b847ac002270f5808146064c995fb6913" integrity sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string.prototype.trimstart@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz#14af6d9f34b053f7cfc89b72f8f2ee14b9039a54" integrity sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string_decoder@^1.1.1: version "1.3.0" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== dependencies: safe-buffer "~5.2.0" string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" stringify-object@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== dependencies: get-own-enumerable-property-symbols "^3.0.0" is-obj "^1.0.1" is-regexp "^1.0.0" strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== dependencies: ansi-regex "^4.1.0" strip-ansi@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== dependencies: ansi-regex "^5.0.0" strip-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.0.tgz#1dc49b980c3a4100366617adac59327eefdefcb0" integrity sha512-UhDTSnGF1dc0DRbUqr1aXwNoY3RgVkSWG8BrpnuFIxhP57IqbS7IRta2Gfiavds4yCxc5+fEAVVOgBZWnYkvzg== dependencies: ansi-regex "^6.0.0" strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= strip-final-newline@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== strip-json-comments@^3.0.1, strip-json-comments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.0.tgz#7638d31422129ecf4457440009fba03f9f9ac180" integrity sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w== strip-json-comments@~3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== sumchecker@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/sumchecker/-/sumchecker-3.0.1.tgz#6377e996795abb0b6d348e9b3e1dfb24345a8e42" integrity sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg== dependencies: debug "^4.1.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" supports-color@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.1.0.tgz#68e32591df73e25ad1c4b49108a2ec507962bfd1" integrity sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g== dependencies: has-flag "^4.0.0" supports-color@^8.0.0: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== dependencies: has-flag "^4.0.0" supports-color@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.0.2.tgz#50f082888e4b0a4e2ccd2d0b4f9ef4efcd332485" integrity sha512-ii6tc8ImGFrgMPYq7RVAMKkhPo9vk8uA+D3oKbJq/3Pk2YSMv1+9dUAesa9UxMbxBTvxwKTQffBahNVNxEvM8Q== dependencies: has-flag "^5.0.0" supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== table@^5.2.3: version "5.4.6" resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e" integrity sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug== dependencies: ajv "^6.10.2" lodash "^4.17.14" slice-ansi "^2.1.0" string-width "^3.0.0" tap-parser@~1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-1.2.2.tgz#5e2f6970611f079c7cf857de1dc7aa1b480de7a5" integrity sha1-Xi9pcGEfB5x8+FfeHceqG0gN56U= dependencies: events-to-array "^1.0.1" inherits "~2.0.1" js-yaml "^3.2.7" optionalDependencies: readable-stream "^2" tap-xunit@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/tap-xunit/-/tap-xunit-2.4.1.tgz#9823797b676ae5017f4e380bd70abb893b8e120e" integrity sha512-qcZStDtjjYjMKAo7QNiCtOW256g3tuSyCSe5kNJniG1Q2oeOExJq4vm8CwboHZURpkXAHvtqMl4TVL7mcbMVVA== dependencies: duplexer "~0.1.1" minimist "~1.2.0" tap-parser "~1.2.2" through2 "~2.0.0" xmlbuilder "~4.2.0" xtend "~4.0.0" tapable@^1.0.0: version "1.1.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== tapable@^2.1.1, tapable@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== tar@^6.1.11: version "6.1.13" resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b" integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw== dependencies: chownr "^2.0.0" fs-minipass "^2.0.0" minipass "^4.0.0" minizlib "^2.1.1" mkdirp "^1.0.3" yallist "^4.0.0" temp@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/temp/-/temp-0.8.3.tgz#e0c6bc4d26b903124410e4fed81103014dfc1f59" integrity sha1-4Ma8TSa5AxJEEOT+2BEDAU38H1k= dependencies: os-tmpdir "^1.0.0" rimraf "~2.2.6" terser-webpack-plugin@^5.1.3: version "5.3.3" resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.3.tgz#8033db876dd5875487213e87c627bca323e5ed90" integrity sha512-Fx60G5HNYknNTNQnzQ1VePRuu89ZVYWfjRAeT5rITuCY/1b08s49e5kSQwHDirKZWuoKOBRFS98EUUoZ9kLEwQ== dependencies: "@jridgewell/trace-mapping" "^0.3.7" jest-worker "^27.4.5" schema-utils "^3.1.1" serialize-javascript "^6.0.0" terser "^5.7.2" terser@^5.7.2: version "5.14.2" resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== dependencies: "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" commander "^2.20.0" source-map-support "~0.5.20" text-table@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= through2@~2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== dependencies: readable-stream "~2.3.6" xtend "~4.0.1" through@^2.3.6, through@^2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= [email protected]: version "1.4.2" resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.4.2.tgz#c9c58b575be8407375cb5e2462dacee74359f41d" integrity sha1-ycWLV1voQHN1y14kYtrO50NZ9B0= dependencies: process "~0.11.0" tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== dependencies: is-number "^7.0.0" to-vfile@^7.0.0: version "7.2.1" resolved "https://registry.yarnpkg.com/to-vfile/-/to-vfile-7.2.1.tgz#fe42892024f724177ba81076f98ee74b0888c293" integrity sha512-biljADNq2n+AZn/zX+/87zStnIqctKr/q5OaOD8+qSKINokUGPbWBShvxa1iLUgHz6dGGjVnQPNoFRtVBzMkVg== dependencies: is-buffer "^2.0.0" vfile "^5.0.0" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== tough-cookie@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.0.0.tgz#d822234eeca882f991f0f908824ad2622ddbece4" integrity sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg== dependencies: psl "^1.1.33" punycode "^2.1.1" universalify "^0.1.2" tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= trough@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/trough/-/trough-2.0.2.tgz#94a3aa9d5ce379fc561f6244905b3f36b7458d96" integrity sha512-FnHq5sTMxC0sk957wHDzRnemFnNBvt/gSY99HzK8F7UP5WAbvP70yX5bd7CjEQkN+TjdxwI7g7lJ6podqrG2/w== ts-loader@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-8.0.2.tgz#ee73ca9350f745799396fff8578ba29b1e95616b" integrity sha512-oYT7wOTUawYXQ8XIDsRhziyW0KUEV38jISYlE+9adP6tDtG+O5GkRe4QKQXrHVH4mJJ88DysvEtvGP65wMLlhg== dependencies: chalk "^2.3.0" enhanced-resolve "^4.0.0" loader-utils "^1.0.2" micromatch "^4.0.0" semver "^6.0.0" [email protected]: version "6.2.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-6.2.0.tgz#65a0ae2acce319ea4fd7ac8d7c9f1f90c5da6baf" integrity sha512-ZNT+OEGfUNVMGkpIaDJJ44Zq3Yr0bkU/ugN1PHbU+/01Z7UV1fsELRiTx1KuQNvQ1A3pGh3y25iYF6jXgxV21A== dependencies: arrify "^1.0.0" buffer-from "^1.1.0" diff "^3.1.0" make-error "^1.1.1" minimist "^1.2.0" mkdirp "^0.5.1" source-map-support "^0.5.6" yn "^2.0.0" tsconfig-paths@^3.9.0: version "3.9.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz#098547a6c4448807e8fcb8eae081064ee9a3c90b" integrity sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw== dependencies: "@types/json5" "^0.0.29" json5 "^1.0.1" minimist "^1.2.0" strip-bom "^3.0.0" tslib@^1.8.1, tslib@^1.9.0: version "1.10.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== tslib@^2.0.0, tslib@^2.2.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== dependencies: tslib "^1.8.1" tunnel@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== dependencies: prelude-ls "^1.2.1" type-check@~0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= dependencies: prelude-ls "~1.1.2" type-detect@^4.0.0, type-detect@^4.0.5: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== type-fest@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.11.0.tgz#97abf0872310fed88a5c466b25681576145e33f1" integrity sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ== type-fest@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934" integrity sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg== type-fest@^0.3.0: version "0.3.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ== type-fest@^0.8.1: version "0.8.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== type-is@~1.6.18: version "1.6.18" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== dependencies: media-typer "0.3.0" mime-types "~2.1.24" typedarray@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= typescript@^4.5.5: version "4.5.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== unified-args@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/unified-args/-/unified-args-9.0.2.tgz#0c14f555e73ee29c23f9a567942e29069f56e5a2" integrity sha512-qSqryjoqfJSII4E4Z2Jx7MhXX2MuUIn6DsrlmL8UnWFdGtrWvEtvm7Rx5fKT5TPUz7q/Fb4oxwIHLCttvAuRLQ== dependencies: "@types/text-table" "^0.2.0" camelcase "^6.0.0" chalk "^4.0.0" chokidar "^3.0.0" fault "^2.0.0" json5 "^2.0.0" minimist "^1.0.0" text-table "^0.2.0" unified-engine "^9.0.0" unified-engine@^9.0.0: version "9.0.3" resolved "https://registry.yarnpkg.com/unified-engine/-/unified-engine-9.0.3.tgz#c1d57e67d94f234296cbfa9364f43e0696dae016" integrity sha512-SgzREcCM2IpUy3JMFUcPRZQ2Py6IwvJ2KIrg2AiI7LnGge6E6OPFWpcabHrEXG0IvO2OI3afiD9DOcQvvZfXDQ== dependencies: "@types/concat-stream" "^1.0.0" "@types/debug" "^4.0.0" "@types/is-empty" "^1.0.0" "@types/js-yaml" "^4.0.0" "@types/node" "^16.0.0" "@types/unist" "^2.0.0" concat-stream "^2.0.0" debug "^4.0.0" fault "^2.0.0" glob "^7.0.0" ignore "^5.0.0" is-buffer "^2.0.0" is-empty "^1.0.0" is-plain-obj "^4.0.0" js-yaml "^4.0.0" load-plugin "^4.0.0" parse-json "^5.0.0" to-vfile "^7.0.0" trough "^2.0.0" unist-util-inspect "^7.0.0" vfile-message "^3.0.0" vfile-reporter "^7.0.0" vfile-statistics "^2.0.0" unified-lint-rule@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/unified-lint-rule/-/unified-lint-rule-1.0.4.tgz#be432d316db7ad801166041727b023ba18963e24" integrity sha512-q9wY6S+d38xRAuWQVOMjBQYi7zGyKkY23ciNafB8JFVmDroyKjtytXHCg94JnhBCXrNqpfojo3+8D+gmF4zxJQ== dependencies: wrapped "^1.0.1" unified-message-control@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unified-message-control/-/unified-message-control-3.0.3.tgz#d08c4564092a507668de71451a33c0d80e734bbd" integrity sha512-oY5z2n8ugjpNHXOmcgrw0pQeJzavHS0VjPBP21tOcm7rc2C+5Q+kW9j5+gqtf8vfW/8sabbsK5+P+9QPwwEHDA== dependencies: unist-util-visit "^2.0.0" vfile-location "^3.0.0" unified@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/unified/-/unified-10.1.0.tgz#4e65eb38fc2448b1c5ee573a472340f52b9346fe" integrity sha512-4U3ru/BRXYYhKbwXV6lU6bufLikoAavTwev89H5UxY8enDFaAT2VXmIXYNm6hb5oHPng/EXr77PVyDFcptbk5g== dependencies: "@types/unist" "^2.0.0" bail "^2.0.0" extend "^3.0.0" is-buffer "^2.0.0" is-plain-obj "^4.0.0" trough "^2.0.0" vfile "^5.0.0" uniq@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" integrity sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8= unist-util-generated@^1.0.0: version "1.1.6" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.6.tgz#5ab51f689e2992a472beb1b35f2ce7ff2f324d4b" integrity sha512-cln2Mm1/CZzN5ttGK7vkoGw+RZ8VcUH6BtGbq98DDtRGquAAOXig1mrBQYelOwMXYS8rK+vZDyyojSjp7JX+Lg== unist-util-generated@^1.1.0: version "1.1.4" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.4.tgz#2261c033d9fc23fae41872cdb7663746e972c1a7" integrity sha512-SA7Sys3h3X4AlVnxHdvN/qYdr4R38HzihoEVY2Q2BZu8NHWDnw5OGcC/tXWjQfd4iG+M6qRFNIRGqJmp2ez4Ww== unist-util-inspect@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/unist-util-inspect/-/unist-util-inspect-7.0.0.tgz#98426f0219e24d011a27e32539be0693d9eb973e" integrity sha512-2Utgv78I7PUu461Y9cdo+IUiiKSKpDV5CE/XD6vTj849a3xlpDAScvSJ6cQmtFBGgAmCn2wR7jLuXhpg1XLlJw== dependencies: "@types/unist" "^2.0.0" unist-util-is@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-4.1.0.tgz#976e5f462a7a5de73d94b706bac1b90671b57797" integrity sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg== unist-util-is@^5.0.0: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-5.1.1.tgz#e8aece0b102fa9bc097b0fef8f870c496d4a6236" integrity sha512-F5CZ68eYzuSvJjGhCLPL3cYx45IxkqXSetCcRgUXtbcm50X2L9oOWQlfUfDdAf+6Pd27YDblBfdtmsThXmwpbQ== unist-util-position@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unist-util-position/-/unist-util-position-3.0.3.tgz#fff942b879538b242096c148153826664b1ca373" integrity sha512-28EpCBYFvnMeq9y/4w6pbnFmCUfzlsc41NJui5c51hOFjBA1fejcwc+5W4z2+0ECVbScG3dURS3JTVqwenzqZw== unist-util-stringify-position@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-2.0.1.tgz#de2a2bc8d3febfa606652673a91455b6a36fb9f3" integrity sha512-Zqlf6+FRI39Bah8Q6ZnNGrEHUhwJOkHde2MHVk96lLyftfJJckaPslKgzhVcviXj8KcE9UJM9F+a4JEiBUTYgA== dependencies: "@types/unist" "^2.0.2" unist-util-stringify-position@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-3.0.0.tgz#d517d2883d74d0daa0b565adc3d10a02b4a8cde9" integrity sha512-SdfAl8fsDclywZpfMDTVDxA2V7LjtRDTOFd44wUJamgl6OlVngsqWjxvermMYf60elWHbxhuRCZml7AnuXCaSA== dependencies: "@types/unist" "^2.0.0" unist-util-visit-parents@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz#65a6ce698f78a6b0f56aa0e88f13801886cdaef6" integrity sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-5.1.1.tgz#868f353e6fce6bf8fa875b251b0f4fec3be709bb" integrity sha512-gks4baapT/kNRaWxuGkl5BIhoanZo7sC/cUT/JToSRNL1dYoXRFl75d++NkjYk4TAu2uv2Px+l8guMajogeuiw== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-2.0.3.tgz#c3703893146df47203bb8a9795af47d7b971208c" integrity sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents "^3.0.0" unist-util-visit@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.1.tgz#1c4842d70bd3df6cc545276f5164f933390a9aad" integrity sha512-n9KN3WV9k4h1DxYR1LoajgN93wpEi/7ZplVe02IoB4gH5ctI1AaF2670BLHQYbwj+pY83gFtyeySFiyMHJklrg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit-parents "^5.1.1" universal-github-app-jwt@^1.0.1: version "1.1.1" resolved "https://registry.yarnpkg.com/universal-github-app-jwt/-/universal-github-app-jwt-1.1.1.tgz#d57cee49020662a95ca750a057e758a1a7190e6e" integrity sha512-G33RTLrIBMFmlDV4u4CBF7dh71eWwykck4XgaxaIVeZKOYZRAAxvcGMRFTUclVY6xoUPQvO4Ne5wKGxYm/Yy9w== dependencies: "@types/jsonwebtoken" "^9.0.0" jsonwebtoken "^9.0.0" universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== universalify@^0.1.0, universalify@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== universalify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d" integrity sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug== universalify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== [email protected], unpipe@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" integrity sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw= update-browserslist-db@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38" integrity sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q== dependencies: escalade "^3.1.1" picocolors "^1.0.0" uri-js@^4.2.2: version "4.4.1" resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== dependencies: punycode "^2.1.0" [email protected]: version "0.10.3" resolved "https://registry.yarnpkg.com/url/-/url-0.10.3.tgz#021e4d9c7705f21bbf37d03ceb58767402774c64" integrity sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ= dependencies: punycode "1.3.2" querystring "0.2.0" util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM= [email protected]: version "3.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131" integrity sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA== uuid@^8.3.0: version "8.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== uvu@^0.5.0: version "0.5.6" resolved "https://registry.yarnpkg.com/uvu/-/uvu-0.5.6.tgz#2754ca20bcb0bb59b64e9985e84d2e81058502df" integrity sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA== dependencies: dequal "^2.0.0" diff "^5.0.0" kleur "^4.0.3" sade "^1.7.3" v8-compile-cache@^2.0.3: version "2.1.1" resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745" integrity sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ== validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" vary@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw= vfile-location@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-3.2.0.tgz#d8e41fbcbd406063669ebf6c33d56ae8721d0f3c" integrity sha512-aLEIZKv/oxuCDZ8lkJGhuhztf/BW4M+iHdCwglA/eWc+vtuRFJj8EtgceYFX4LRjOhCAAiNHsKGssC6onJ+jbA== vfile-message@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.0.1.tgz#b9bcf87cb5525e61777e0c6df07e816a577588a3" integrity sha512-gYmSHcZZUEtYpTmaWaFJwsuUD70/rTY4v09COp8TGtOkix6gGxb/a8iTQByIY9ciTk9GwAwIXd/J9OPfM4Bvaw== dependencies: "@types/unist" "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-reporter@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.1.tgz#759bfebb995f3dc8c644284cb88ac4b310ebd168" integrity sha512-pof+cQSJCUNmHG6zoBOJfErb6syIWHWM14CwKjsugCixxl4CZdrgzgxwLBW8lIB6czkzX0Agnnhj33YpKyLvmA== dependencies: "@types/repeat-string" "^1.0.0" "@types/supports-color" "^8.0.0" repeat-string "^1.0.0" string-width "^5.0.0" supports-color "^9.0.0" unist-util-stringify-position "^3.0.0" vfile-sort "^3.0.0" vfile-statistics "^2.0.0" vfile-sort@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/vfile-sort/-/vfile-sort-3.0.0.tgz#ee13d3eaac0446200a2047a3b45d78fad6b106e6" integrity sha512-fJNctnuMi3l4ikTVcKpxTbzHeCgvDhnI44amA3NVDvA6rTC6oKCFpCVyT5n2fFMr3ebfr+WVQZedOCd73rzSxg== dependencies: vfile-message "^3.0.0" vfile-statistics@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/vfile-statistics/-/vfile-statistics-2.0.0.tgz#f04ee3e3c666809a3c10c06021becd41ea9c8037" integrity sha512-foOWtcnJhKN9M2+20AOTlWi2dxNfAoeNIoxD5GXcO182UJyId4QrXa41fWrgcfV3FWTjdEDy3I4cpLVcQscIMA== dependencies: vfile-message "^3.0.0" vfile@^5.0.0: version "5.0.2" resolved "https://registry.yarnpkg.com/vfile/-/vfile-5.0.2.tgz#57773d1d91478b027632c23afab58ec3590344f0" integrity sha512-5cV+K7tX83MT3bievROc+7AvHv0GXDB0zqbrTjbOe+HRbkzvY4EP+wS3IR77kUBCoWFMdG9py18t0sesPtQ1Rw== dependencies: "@types/unist" "^2.0.0" is-buffer "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" [email protected]: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz#f239ed2cd6004021b6550af9fd9d3e47eee3cac9" integrity sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ== [email protected]: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz#beaa46aea06ed061576586c5e11368a9afc1d378" integrity sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg== dependencies: vscode-jsonrpc "8.0.2" vscode-languageserver-types "3.17.2" vscode-languageserver-textdocument@^1.0.5, vscode-languageserver-textdocument@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz#16df468d5c2606103c90554ae05f9f3d335b771b" integrity sha512-bFJH7UQxlXT8kKeyiyu41r22jCZXG8kuuVVA33OEJn1diWOZK5n8zBSPZFHVBOu8kXZ6h0LIRhf5UnCo61J4Hg== [email protected], vscode-languageserver-types@^3.17.1: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz#b2c2e7de405ad3d73a883e91989b850170ffc4f2" integrity sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA== vscode-languageserver@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.0.2.tgz#cfe2f0996d9dfd40d3854e786b2821604dfec06d" integrity sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA== dependencies: vscode-languageserver-protocol "3.17.2" vscode-uri@^3.0.3, vscode-uri@^3.0.6: version "3.0.6" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.6.tgz#5e6e2e1a4170543af30151b561a41f71db1d6f91" integrity sha512-fmL7V1eiDBFRRnu+gfRWTzyPpNIHJTc4mWnFkwBUmO9U3KPgJAmTx7oxi2bl/Rh6HLdU7+4C9wlj0k2E4AdKFQ== walk-sync@^0.3.2: version "0.3.4" resolved "https://registry.yarnpkg.com/walk-sync/-/walk-sync-0.3.4.tgz#cf78486cc567d3a96b5b2237c6108017a5ffb9a4" integrity sha512-ttGcuHA/OBnN2pcM6johpYlEms7XpO5/fyKIr48541xXedan4roO8cS1Q2S/zbbjGH/BarYDAMeS2Mi9HE5Tig== dependencies: ensure-posix-path "^1.0.0" matcher-collection "^1.0.0" watchpack@^2.3.1: version "2.4.0" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" integrity sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g= dependencies: defaults "^1.0.3" webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE= webpack-cli@^4.10.0: version "4.10.0" resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== dependencies: "@discoveryjs/json-ext" "^0.5.0" "@webpack-cli/configtest" "^1.2.0" "@webpack-cli/info" "^1.5.0" "@webpack-cli/serve" "^1.7.0" colorette "^2.0.14" commander "^7.0.0" cross-spawn "^7.0.3" fastest-levenshtein "^1.0.12" import-local "^3.0.2" interpret "^2.2.0" rechoir "^0.7.0" webpack-merge "^5.7.3" webpack-merge@^5.7.3: version "5.8.0" resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" integrity sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q== dependencies: clone-deep "^4.0.1" wildcard "^2.0.0" webpack-sources@^3.2.3: version "3.2.3" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== webpack@^5, webpack@^5.73.0: version "5.73.0" resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.73.0.tgz#bbd17738f8a53ee5760ea2f59dce7f3431d35d38" integrity sha512-svjudQRPPa0YiOYa2lM/Gacw0r6PvxptHj4FuEKQ2kX05ZLkjbVc5MnPs6its5j7IZljnIqSVo/OsY2X0IpHGA== dependencies: "@types/eslint-scope" "^3.7.3" "@types/estree" "^0.0.51" "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/wasm-edit" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" acorn "^8.4.1" acorn-import-assertions "^1.7.6" browserslist "^4.14.5" chrome-trace-event "^1.0.2" enhanced-resolve "^5.9.3" es-module-lexer "^0.9.0" eslint-scope "5.1.1" events "^3.2.0" glob-to-regexp "^0.4.1" graceful-fs "^4.2.9" json-parse-even-better-errors "^2.3.1" loader-runner "^4.2.0" mime-types "^2.1.27" neo-async "^2.6.2" schema-utils "^3.1.0" tapable "^2.1.1" terser-webpack-plugin "^5.1.3" watchpack "^2.3.1" webpack-sources "^3.2.3" whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" integrity sha1-lmRU6HZUYuN2RNNib2dCzotwll0= dependencies: tr46 "~0.0.3" webidl-conversions "^3.0.0" which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" which@^2.0.1: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" wildcard@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== word-wrap@^1.2.3, word-wrap@~1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== wrap-ansi@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== dependencies: ansi-styles "^4.0.0" string-width "^4.1.0" strip-ansi "^6.0.0" wrapped@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wrapped/-/wrapped-1.0.1.tgz#c783d9d807b273e9b01e851680a938c87c907242" integrity sha1-x4PZ2Aeyc+mwHoUWgKk4yHyQckI= dependencies: co "3.1.0" sliced "^1.0.1" wrapper-webpack-plugin@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/wrapper-webpack-plugin/-/wrapper-webpack-plugin-2.2.2.tgz#a950b7fbc39ca103e468a7c06c225cb1e337ad3b" integrity sha512-twLGZw0b2AEnz3LmsM/uCFRzGxE+XUlUPlJkCuHY3sI+uGO4dTJsgYee3ufWJaynAZYkpgQSKMSr49n9Yxalzg== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= [email protected]: version "1.0.3" resolved "https://registry.yarnpkg.com/write/-/write-1.0.3.tgz#0800e14523b923a387e415123c865616aae0f5c3" integrity sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig== dependencies: mkdirp "^0.5.1" [email protected]: version "0.4.19" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.19.tgz#686c20f213209e94abf0d1bcf1efaa291c7827a7" integrity sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q== dependencies: sax ">=0.6.0" xmlbuilder "~9.0.1" xml2js@^0.4.19: version "0.4.23" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.23.tgz#a0c69516752421eb2ac758ee4d4ccf58843eac66" integrity sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug== dependencies: sax ">=0.6.0" xmlbuilder "~11.0.0" xmlbuilder@~11.0.0: version "11.0.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== xmlbuilder@~4.2.0: version "4.2.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5" integrity sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU= dependencies: lodash "^4.0.0" xmlbuilder@~9.0.1: version "9.0.7" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-9.0.7.tgz#132ee63d2ec5565c557e20f4c22df9aca686b10d" integrity sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0= xtend@^4.0.1, xtend@~4.0.0, xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== yallist@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== yaml@^1.7.2: version "1.10.0" resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9" integrity sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g== dependencies: buffer-crc32 "~0.2.3" fd-slicer "~1.1.0" yn@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/yn/-/yn-2.0.0.tgz#e5adabc8acf408f6385fc76495684c88e6af689a" integrity sha1-5a2ryKz0CPY4X8dklWhMiOavaJo= zwitch@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.2.tgz#91f8d0e901ffa3d66599756dde7f57b17c95dce1" integrity sha512-JZxotl7SxAJH0j7dN4pxsTV6ZLXoLdGME+PsjkL/DaBrVryK9kTGq06GfKrwcSOqypP+fdXGoCHE36b99fWVoA==
closed
electron/electron
https://github.com/electron/electron
16,446
Widevine not working on Electron 4.0.1
I need Widevine on electron app I copied the widevinecdm.dll from Google Chrome. The CDM minimum version support is 68.0.3430.0 Widevine version 4.10.1224.7 On main.js `app.commandLine.appendSwitch('widevine-cdm-path', path.join(__dirname, 'widevinecdm.dll')); app.commandLine.appendSwitch('widevine-cdm-version', 4.10.1224.7);` and then `win = new BrowserWindow({ width:1000, height:800, webPreferences: { plugins: true} }); win.loadURL("http://www.dash-player.com/demo/drm-test-area/")` But this page shows NO Drm Support
https://github.com/electron/electron/issues/16446
https://github.com/electron/electron/pull/37583
caa5989eedd44625dad508c9665b8032df01e235
94f701edb8212d2bc5103bddc8077c5f5bcd2f6c
2019-01-18T13:54:14Z
c++
2023-03-20T17:33:08Z
package.json
{ "name": "electron", "version": "0.0.0-development", "repository": "https://github.com/electron/electron", "description": "Build cross platform desktop apps with JavaScript, HTML, and CSS", "devDependencies": { "@azure/storage-blob": "^12.9.0", "@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4", "@electron/asar": "^3.2.1", "@electron/docs-parser": "^1.1.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^1.5.0", "@electron/typescript-definitions": "^8.14.0", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", "@types/basic-auth": "^1.1.3", "@types/busboy": "^1.5.0", "@types/chai": "^4.2.12", "@types/chai-as-promised": "^7.1.3", "@types/dirty-chai": "^2.0.2", "@types/express": "^4.17.13", "@types/fs-extra": "^9.0.1", "@types/klaw": "^3.0.1", "@types/minimist": "^1.2.0", "@types/mocha": "^7.0.2", "@types/node": "^18.11.18", "@types/semver": "^7.3.3", "@types/send": "^0.14.5", "@types/split": "^1.0.0", "@types/stream-json": "^1.5.1", "@types/temp": "^0.8.34", "@types/uuid": "^3.4.6", "@types/webpack": "^5.28.0", "@types/webpack-env": "^1.17.0", "@typescript-eslint/eslint-plugin": "^4.4.1", "@typescript-eslint/parser": "^4.4.1", "aws-sdk": "^2.814.0", "buffer": "^6.0.3", "check-for-leaks": "^1.2.1", "colors": "1.4.0", "dotenv-safe": "^4.0.4", "dugite": "^2.3.0", "eslint": "^7.4.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.22.0", "eslint-plugin-mocha": "^7.0.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-standard": "^4.0.1", "eslint-plugin-typescript": "^0.14.0", "events": "^3.2.0", "express": "^4.16.4", "folder-hash": "^2.1.1", "fs-extra": "^9.0.1", "got": "^11.8.5", "husky": "^8.0.1", "klaw": "^3.0.0", "lint": "^1.1.2", "lint-staged": "^10.2.11", "markdownlint-cli": "^0.33.0", "mdast-util-from-markdown": "^1.2.0", "minimist": "^1.2.6", "null-loader": "^4.0.0", "pre-flight": "^1.1.0", "process": "^0.11.10", "remark-cli": "^10.0.0", "remark-preset-lint-markdown-style-guide": "^4.0.0", "semver": "^5.6.0", "shx": "^0.3.2", "standard-markdown": "^6.0.0", "stream-json": "^1.7.1", "tap-xunit": "^2.4.1", "temp": "^0.8.3", "timers-browserify": "1.4.2", "ts-loader": "^8.0.2", "ts-node": "6.2.0", "typescript": "^4.5.5", "unist-util-visit": "^4.1.1", "vscode-languageserver": "^8.0.2", "vscode-languageserver-textdocument": "^1.0.7", "vscode-uri": "^3.0.6", "webpack": "^5.73.0", "webpack-cli": "^4.10.0", "wrapper-webpack-plugin": "^2.2.0" }, "private": true, "scripts": { "asar": "asar", "generate-version-json": "node script/generate-version-json.js", "lint": "node ./script/lint.js && npm run lint:docs", "lint:js": "node ./script/lint.js --js", "lint:clang-format": "python3 script/run-clang-format.py -r -c shell/ || (echo \"\\nCode not formatted correctly.\" && exit 1)", "lint:clang-tidy": "ts-node ./script/run-clang-tidy.ts", "lint:cpp": "node ./script/lint.js --cc", "lint:objc": "node ./script/lint.js --objc", "lint:py": "node ./script/lint.js --py", "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-relative-links && npm run lint:markdownlint", "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs", "create-api-json": "node script/create-api-json.js", "create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js", "gn-typescript-definitions": "npm run create-typescript-definitions && shx cp electron.d.ts", "pre-flight": "pre-flight", "gn-check": "node ./script/gn-check.js", "gn-format": "python3 script/run-gn-format.py", "precommit": "lint-staged", "preinstall": "node -e 'process.exit(0)'", "prepack": "check-for-leaks", "prepare": "husky install", "repl": "node ./script/start.js --interactive", "start": "node ./script/start.js", "test": "node ./script/spec-runner.js", "tsc": "tsc", "webpack": "webpack" }, "license": "MIT", "author": "Electron Community", "keywords": [ "electron" ], "lint-staged": { "*.{js,ts}": [ "node script/lint.js --js --fix --only --" ], "*.{js,ts,d.ts}": [ "ts-node script/gen-filenames.ts" ], "*.{cc,mm,c,h}": [ "python3 script/run-clang-format.py -r -c --fix" ], "*.md": [ "npm run lint:docs" ], "*.{gn,gni}": [ "npm run gn-check", "npm run gn-format" ], "*.py": [ "node script/lint.js --py --fix --only --" ], "docs/api/**/*.md": [ "ts-node script/gen-filenames.ts", "markdownlint --config .markdownlint.autofix.json --fix", "git add filenames.auto.gni" ], "{*.patch,.patches}": [ "node script/lint.js --patches --only --", "ts-node script/check-patch-diff.ts" ], "DEPS": [ "node script/gen-hunspell-filenames.js", "node script/gen-libc++-filenames.js" ] }, "resolutions": { "nan": "nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac" } }
closed
electron/electron
https://github.com/electron/electron
16,446
Widevine not working on Electron 4.0.1
I need Widevine on electron app I copied the widevinecdm.dll from Google Chrome. The CDM minimum version support is 68.0.3430.0 Widevine version 4.10.1224.7 On main.js `app.commandLine.appendSwitch('widevine-cdm-path', path.join(__dirname, 'widevinecdm.dll')); app.commandLine.appendSwitch('widevine-cdm-version', 4.10.1224.7);` and then `win = new BrowserWindow({ width:1000, height:800, webPreferences: { plugins: true} }); win.loadURL("http://www.dash-player.com/demo/drm-test-area/")` But this page shows NO Drm Support
https://github.com/electron/electron/issues/16446
https://github.com/electron/electron/pull/37583
caa5989eedd44625dad508c9665b8032df01e235
94f701edb8212d2bc5103bddc8077c5f5bcd2f6c
2019-01-18T13:54:14Z
c++
2023-03-20T17:33:08Z
yarn.lock
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@azure/abort-controller@^1.0.0": version "1.0.4" resolved "https://registry.yarnpkg.com/@azure/abort-controller/-/abort-controller-1.0.4.tgz#fd3c4d46c8ed67aace42498c8e2270960250eafd" integrity sha512-lNUmDRVGpanCsiUN3NWxFTdwmdFI53xwhkTFfHDGTYk46ca7Ind3nanJc+U6Zj9Tv+9nTCWRBscWEW1DyKOpTw== dependencies: tslib "^2.0.0" "@azure/core-asynciterator-polyfill@^1.0.0": version "1.0.2" resolved "https://registry.yarnpkg.com/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.2.tgz#0dd3849fb8d97f062a39db0e5cadc9ffaf861fec" integrity sha512-3rkP4LnnlWawl0LZptJOdXNrT/fHp2eQMadoasa6afspXdpGrtPZuAQc2PD0cpgyuoXtUWyC3tv7xfntjGS5Dw== "@azure/core-auth@^1.3.0": version "1.3.2" resolved "https://registry.yarnpkg.com/@azure/core-auth/-/core-auth-1.3.2.tgz#6a2c248576c26df365f6c7881ca04b7f6d08e3d0" integrity sha512-7CU6DmCHIZp5ZPiZ9r3J17lTKMmYsm/zGvNkjArQwPkrLlZ1TZ+EUYfGgh2X31OLMVAQCTJZW4cXHJi02EbJnA== dependencies: "@azure/abort-controller" "^1.0.0" tslib "^2.2.0" "@azure/core-http@^2.0.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-http/-/core-http-2.2.4.tgz#df5a5b4138dbbc4299879f2fc6f257d0a5f0401e" integrity sha512-QmmJmexXKtPyc3/rsZR/YTLDvMatzbzAypJmLzvlfxgz/SkgnqV/D4f6F2LsK6tBj1qhyp8BoXiOebiej0zz3A== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-asynciterator-polyfill" "^1.0.0" "@azure/core-auth" "^1.3.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" "@types/node-fetch" "^2.5.0" "@types/tunnel" "^0.0.3" form-data "^4.0.0" node-fetch "^2.6.7" process "^0.11.10" tough-cookie "^4.0.0" tslib "^2.2.0" tunnel "^0.0.6" uuid "^8.3.0" xml2js "^0.4.19" "@azure/core-lro@^2.2.0": version "2.2.4" resolved "https://registry.yarnpkg.com/@azure/core-lro/-/core-lro-2.2.4.tgz#42fbf4ae98093c59005206a4437ddcd057c57ca1" integrity sha512-e1I2v2CZM0mQo8+RSix0x091Av493e4bnT22ds2fcQGslTHzM2oTbswkB65nP4iEpCxBrFxOSDPKExmTmjCVtQ== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" tslib "^2.2.0" "@azure/core-paging@^1.1.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@azure/core-paging/-/core-paging-1.2.1.tgz#1b884f563b6e49971e9a922da3c7a20931867b54" integrity sha512-UtH5iMlYsvg+nQYIl4UHlvvSrsBjOlRF4fs0j7mxd3rWdAStrKYrh2durOpHs5C9yZbVhsVDaisoyaf/lL1EVA== dependencies: "@azure/core-asynciterator-polyfill" "^1.0.0" tslib "^2.2.0" "@azure/[email protected]": version "1.0.0-preview.13" resolved "https://registry.yarnpkg.com/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz#55883d40ae2042f6f1e12b17dd0c0d34c536d644" integrity sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ== dependencies: "@opentelemetry/api" "^1.0.1" tslib "^2.2.0" "@azure/logger@^1.0.0": version "1.0.3" resolved "https://registry.yarnpkg.com/@azure/logger/-/logger-1.0.3.tgz#6e36704aa51be7d4a1bae24731ea580836293c96" integrity sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g== dependencies: tslib "^2.2.0" "@azure/storage-blob@^12.9.0": version "12.9.0" resolved "https://registry.yarnpkg.com/@azure/storage-blob/-/storage-blob-12.9.0.tgz#4cbd8b4c7a47dd064867430db892f4ef2d8f17ab" integrity sha512-ank38FdCLfJ+EoeMzCz3hkYJuZAd63ARvDKkxZYRDb+beBYf+/+gx8jNTqkq/hfyUl4dJQ/a7tECU0Y0F98CHg== dependencies: "@azure/abort-controller" "^1.0.0" "@azure/core-http" "^2.0.0" "@azure/core-lro" "^2.2.0" "@azure/core-paging" "^1.1.1" "@azure/core-tracing" "1.0.0-preview.13" "@azure/logger" "^1.0.0" events "^3.0.0" tslib "^2.2.0" "@babel/code-frame@^7.0.0": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw== dependencies: "@babel/highlight" "^7.0.0" "@babel/highlight@^7.0.0": version "7.5.0" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.5.0.tgz#56d11312bd9248fa619591d02472be6e8cb32540" integrity sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ== dependencies: chalk "^2.0.0" esutils "^2.0.2" js-tokens "^4.0.0" "@discoveryjs/json-ext@^0.5.0": version "0.5.7" resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== "@dsanders11/vscode-markdown-languageservice@^0.3.0-alpha.4": version "0.3.0-alpha.4" resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0-alpha.4.tgz#cd80b82142a2c10e09b5f36a93c3ea65b7d2a7f9" integrity sha512-MHp/CniEkzJb1CAw/bHwucuImaICrcIuohEFamTW8sJC2jhKCnbYblwJFZ3OOS3wTYZbzFIa8WZ4Dn5yL2E7jg== dependencies: "@vscode/l10n" "^0.0.10" picomatch "^2.3.1" vscode-languageserver-textdocument "^1.0.5" vscode-languageserver-types "^3.17.1" vscode-uri "^3.0.3" "@electron/asar@^3.2.1": version "3.2.1" resolved "https://registry.yarnpkg.com/@electron/asar/-/asar-3.2.1.tgz#c4143896f3dd43b59a80a9c9068d76f77efb62ea" integrity sha512-hE2cQMZ5+4o7+6T2lUaVbxIzrOjZZfX7dB02xuapyYFJZEAiWTelq6J3mMoxzd0iONDvYLPVKecB5tyjIoVDVA== dependencies: chromium-pickle-js "^0.2.0" commander "^5.0.0" glob "^7.1.6" minimatch "^3.0.4" optionalDependencies: "@types/glob" "^7.1.1" "@electron/docs-parser@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@electron/docs-parser/-/docs-parser-1.1.0.tgz#ba095def41746bde56bee731feaf22272bf0b765" integrity sha512-qrjIKJk8t4/xAYldDVNQgcF8zdAAuG260bzPxdh/xI3p/yddm61bftoct+Tx2crnWFnOfOkr6nGERsDknNiT8A== dependencies: "@types/markdown-it" "^12.0.0" chai "^4.2.0" chalk "^3.0.0" fs-extra "^8.1.0" lodash.camelcase "^4.3.0" markdown-it "^12.0.0" minimist "^1.2.0" ora "^4.0.3" pretty-ms "^5.1.0" "@electron/fiddle-core@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@electron/fiddle-core/-/fiddle-core-1.0.4.tgz#d28e330c4d88f3916269558a43d214c4312333af" integrity sha512-gjPz3IAHK+/f0N52cWVeTZpdgENJo3QHBGeGqMDHFUgzSBRTVyAr8z8Lw8wpu6Ocizs154Rtssn4ba1ysABgLA== dependencies: "@electron/get" "^2.0.0" debug "^4.3.3" env-paths "^2.2.1" extract-zip "^2.0.1" fs-extra "^10.0.0" getos "^3.2.1" node-fetch "^2.6.1" semver "^7.3.5" simple-git "^3.5.0" "@electron/get@^2.0.0": version "2.0.2" resolved "https://registry.yarnpkg.com/@electron/get/-/get-2.0.2.tgz#ae2a967b22075e9c25aaf00d5941cd79c21efd7e" integrity sha512-eFZVFoRXb3GFGd7Ak7W4+6jBl9wBtiZ4AaYOse97ej6mKj5tkyO0dUnUChs1IhJZtx1BENo4/p4WUTXpi6vT+g== dependencies: debug "^4.1.1" env-paths "^2.2.0" fs-extra "^8.1.0" got "^11.8.5" progress "^2.0.3" semver "^6.2.0" sumchecker "^3.0.1" optionalDependencies: global-agent "^3.0.0" "@electron/github-app-auth@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@electron/github-app-auth/-/github-app-auth-1.5.0.tgz#426e64ba50143417d9b68f2795a1b119cb62108b" integrity sha512-t6Za+3E7jdIf1CX06nNV/avZhqSXNEkCLJ1xeAt5FKU9HdGbjzwSfirM+UlHO7lMGyuf13BGCZOCB1kODhDLWQ== dependencies: "@octokit/auth-app" "^3.6.1" "@octokit/rest" "^18.12.0" "@electron/typescript-definitions@^8.14.0": version "8.14.0" resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.14.0.tgz#a88f74e915317ba943b57ffe499b319d04f01ee3" integrity sha512-J3b4is6L0NB4+r+7s1Hl1YlzaveKnQt1gswadRyMRwb4gFU3VAe2oBMJLOhFRJMs/9PK/Xp+y9QwyC92Tyqe6A== dependencies: "@types/node" "^11.13.7" chalk "^2.4.2" colors "^1.1.2" debug "^4.1.1" fs-extra "^7.0.1" lodash "^4.17.11" minimist "^1.2.0" mkdirp "^0.5.1" ora "^3.4.0" pretty-ms "^5.0.0" "@jridgewell/gen-mapping@^0.3.0": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== dependencies: "@jridgewell/set-array" "^1.0.1" "@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/resolve-uri@^3.0.3": version "3.1.0" resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== "@jridgewell/source-map@^0.3.2": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== dependencies: "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== "@jridgewell/trace-mapping@^0.3.7", "@jridgewell/trace-mapping@^0.3.9": version "0.3.14" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.14.tgz#b231a081d8f66796e475ad588a1ef473112701ed" integrity sha512-bJWEfQ9lPTvm3SneWwRFVLzrh6nhjwqw7TUFFBEMzwvg7t7PCDenf2lDwqo4NQXzdpgBXyFgDWnQA+2vkruksQ== dependencies: "@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/sourcemap-codec" "^1.4.10" "@kwsites/file-exists@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/file-exists/-/file-exists-1.1.1.tgz#ad1efcac13e1987d8dbaf235ef3be5b0d96faa99" integrity sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw== dependencies: debug "^4.1.1" "@kwsites/promise-deferred@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz#8ace5259254426ccef57f3175bc64ed7095ed919" integrity sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw== "@nodelib/[email protected]": version "2.1.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz#3a582bdb53804c6ba6d146579c46e52130cf4a3b" integrity sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw== dependencies: "@nodelib/fs.stat" "2.0.3" run-parallel "^1.1.9" "@nodelib/[email protected]", "@nodelib/fs.stat@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz#34dc5f4cabbc720f4e60f75a747e7ecd6c175bd3" integrity sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA== "@nodelib/fs.walk@^1.2.3": version "1.2.4" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz#011b9202a70a6366e436ca5c065844528ab04976" integrity sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ== dependencies: "@nodelib/fs.scandir" "2.1.3" fastq "^1.6.0" "@octokit/auth-app@^3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@octokit/auth-app/-/auth-app-3.6.1.tgz#aa5b02cc211175cbc28ce6c03c73373c1206d632" integrity sha512-6oa6CFphIYI7NxxHrdVOzhG7hkcKyGyYocg7lNDSJVauVOLtylg8hNJzoUyPAYKKK0yUeoZamE/lMs2tG+S+JA== dependencies: "@octokit/auth-oauth-app" "^4.3.0" "@octokit/auth-oauth-user" "^1.2.3" "@octokit/request" "^5.6.0" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.0.3" "@types/lru-cache" "^5.1.0" deprecation "^2.3.1" lru-cache "^6.0.0" universal-github-app-jwt "^1.0.1" universal-user-agent "^6.0.0" "@octokit/auth-oauth-app@^4.3.0": version "4.3.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-app/-/auth-oauth-app-4.3.4.tgz#7030955b1a59d4d977904775c606477d95fcfe8e" integrity sha512-OYOTSSINeUAiLMk1uelaGB/dEkReBqHHr8+hBejzMG4z1vA4c7QSvDAS0RVZSr4oD4PEUPYFzEl34K7uNrXcWA== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/auth-oauth-user" "^2.0.0" "@octokit/request" "^5.6.3" "@octokit/types" "^6.0.3" "@types/btoa-lite" "^1.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^3.1.1": version "3.1.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-3.1.4.tgz#703c42f27a1e2eb23498a7001ad8e9ecf4a2f477" integrity sha512-6sHE/++r+aEFZ/BKXOGPJcH/nbgbBjS1A4CHfq/PbPEwb0kZEt43ykW98GBO/rYBPAYaNpCPvXfGwzgR9yMCXg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^6.10.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-device@^4.0.0": version "4.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.3.tgz#00ce77233517e0d7d39e42a02652f64337d9df81" integrity sha512-KPTx5nMntKjNZzzltO3X4T68v22rd7Cp/TcLJXQE2U8aXPcZ9LFuww9q9Q5WUNSu3jwi3lRwzfkPguRfz1R8Vg== dependencies: "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^1.2.3": version "1.3.0" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-1.3.0.tgz#da4e4529145181a6aa717ae858afb76ebd6e3360" integrity sha512-3QC/TAdk7onnxfyZ24BnJRfZv8TRzQK7SEFUS9vLng4Vv6Hv6I64ujdk/CUkREec8lhrwU764SZ/d+yrjjqhaQ== dependencies: "@octokit/auth-oauth-device" "^3.1.1" "@octokit/oauth-methods" "^1.1.0" "@octokit/request" "^5.4.14" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-oauth-user@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/auth-oauth-user/-/auth-oauth-user-2.0.4.tgz#88f060ec678d7d493695af8d827e115dd064e212" integrity sha512-HrbDzTPqz6GcGSOUkR+wSeF3vEqsb9NMsmPja/qqqdiGmlk/Czkxctc3KeWYogHonp62Ml4kjz2VxKawrFsadQ== dependencies: "@octokit/auth-oauth-device" "^4.0.0" "@octokit/oauth-methods" "^2.0.0" "@octokit/request" "^6.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" universal-user-agent "^6.0.0" "@octokit/auth-token@^2.4.4": version "2.5.0" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36" integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g== dependencies: "@octokit/types" "^6.0.3" "@octokit/auth-token@^3.0.0": version "3.0.3" resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-3.0.3.tgz#ce7e48a3166731f26068d7a7a7996b5da58cbe0c" integrity sha512-/aFM2M4HVDBT/jjDBa84sJniv1t9Gm/rLkalaz9htOm+L+8JMj1k9w0CkUdcxNyNxZPlTxKPVko+m1VlM58ZVA== dependencies: "@octokit/types" "^9.0.0" "@octokit/core@^3.5.1": version "3.6.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.6.0.tgz#3376cb9f3008d9b3d110370d90e0a1fcd5fe6085" integrity sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q== dependencies: "@octokit/auth-token" "^2.4.4" "@octokit/graphql" "^4.5.8" "@octokit/request" "^5.6.3" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.0.3" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/core@^4.1.0": version "4.2.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-4.2.0.tgz#8c253ba9605aca605bc46187c34fcccae6a96648" integrity sha512-AgvDRUg3COpR82P7PBdGZF/NNqGmtMq2NiPqeSsDIeCfYFOZ9gddqWNQHnFdEUf+YwOj4aZYmJnlPp7OXmDIDg== dependencies: "@octokit/auth-token" "^3.0.0" "@octokit/graphql" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^9.0.0" before-after-hook "^2.2.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^6.0.1": version "6.0.5" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.5.tgz#43a6adee813c5ffd2f719e20cfd14a1fee7c193a" integrity sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ== dependencies: "@octokit/types" "^5.0.0" is-plain-object "^4.0.0" universal-user-agent "^6.0.0" "@octokit/endpoint@^7.0.0": version "7.0.3" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-7.0.3.tgz#0b96035673a9e3bedf8bab8f7335de424a2147ed" integrity sha512-57gRlb28bwTsdNXq+O3JTQ7ERmBTuik9+LelgcLIVfYwf235VHbN9QNo4kXExtp/h8T423cR5iJThKtFYxC7Lw== dependencies: "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" universal-user-agent "^6.0.0" "@octokit/graphql@^4.5.8": version "4.8.0" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3" integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg== dependencies: "@octokit/request" "^5.6.0" "@octokit/types" "^6.0.3" universal-user-agent "^6.0.0" "@octokit/graphql@^5.0.0": version "5.0.5" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-5.0.5.tgz#a4cb3ea73f83b861893a6370ee82abb36e81afd2" integrity sha512-Qwfvh3xdqKtIznjX9lz2D458r7dJPP8l6r4GQkIdWQouZwHQK0mVT88uwiU2bdTU2OtT1uOlKpRciUWldpG0yQ== dependencies: "@octokit/request" "^6.0.0" "@octokit/types" "^9.0.0" universal-user-agent "^6.0.0" "@octokit/oauth-authorization-url@^4.3.1": version "4.3.3" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-4.3.3.tgz#6a6ef38f243086fec882b62744f39b517528dfb9" integrity sha512-lhP/t0i8EwTmayHG4dqLXgU+uPVys4WD/qUNvC+HfB1S1dyqULm5Yx9uKc1x79aP66U1Cb4OZeW8QU/RA9A4XA== "@octokit/oauth-authorization-url@^5.0.0": version "5.0.0" resolved "https://registry.yarnpkg.com/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz#029626ce87f3b31addb98cd0d2355c2381a1c5a1" integrity sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg== "@octokit/oauth-methods@^1.1.0": version "1.2.6" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-1.2.6.tgz#b9ac65e374b2cc55ee9dd8dcdd16558550438ea7" integrity sha512-nImHQoOtKnSNn05uk2o76om1tJWiAo4lOu2xMAHYsNr0fwopP+Dv+2MlGvaMMlFjoqVd3fF3X5ZDTKCsqgmUaQ== dependencies: "@octokit/oauth-authorization-url" "^4.3.1" "@octokit/request" "^5.4.14" "@octokit/request-error" "^2.0.5" "@octokit/types" "^6.12.2" btoa-lite "^1.0.0" "@octokit/oauth-methods@^2.0.0": version "2.0.4" resolved "https://registry.yarnpkg.com/@octokit/oauth-methods/-/oauth-methods-2.0.4.tgz#6abd9593ca7f91fe5068375a363bd70abd5516dc" integrity sha512-RDSa6XL+5waUVrYSmOlYROtPq0+cfwppP4VaQY/iIei3xlFb0expH6YNsxNrZktcLhJWSpm9uzeom+dQrXlS3A== dependencies: "@octokit/oauth-authorization-url" "^5.0.0" "@octokit/request" "^6.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" btoa-lite "^1.0.0" "@octokit/openapi-types@^12.11.0": version "12.11.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.11.0.tgz#da5638d64f2b919bca89ce6602d059f1b52d3ef0" integrity sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ== "@octokit/openapi-types@^14.0.0": version "14.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-14.0.0.tgz#949c5019028c93f189abbc2fb42f333290f7134a" integrity sha512-HNWisMYlR8VCnNurDU6os2ikx0s0VyEjDYHNS/h4cgb8DeOxQ0n72HyinUtdDVxJhFy3FWLGl0DJhfEWk3P5Iw== "@octokit/openapi-types@^16.0.0": version "16.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-16.0.0.tgz#d92838a6cd9fb4639ca875ddb3437f1045cc625e" integrity sha512-JbFWOqTJVLHZSUUoF4FzAZKYtqdxWu9Z5m2QQnOyEa04fOFljvyh7D3GYKbfuaSWisqehImiVIMG4eyJeP5VEA== "@octokit/plugin-paginate-rest@^2.16.8": version "2.21.3" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.3.tgz#7f12532797775640dbb8224da577da7dc210c87e" integrity sha512-aCZTEf0y2h3OLbrgKkrfFdjRL6eSOo8komneVQJnYecAxIej7Bafor2xhuDJOIFau4pk0i/P28/XgtbyPF0ZHw== dependencies: "@octokit/types" "^6.40.0" "@octokit/plugin-paginate-rest@^6.0.0": version "6.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.0.0.tgz#f34b5a7d9416019126042cd7d7b811e006c0d561" integrity sha512-Sq5VU1PfT6/JyuXPyt04KZNVsFOSBaYOAq2QRZUwzVlI10KFvcbUo8lR258AAQL1Et60b0WuVik+zOWKLuDZxw== dependencies: "@octokit/types" "^9.0.0" "@octokit/plugin-request-log@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85" integrity sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA== "@octokit/plugin-rest-endpoint-methods@^5.12.0": version "5.16.2" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.2.tgz#7ee8bf586df97dd6868cf68f641354e908c25342" integrity sha512-8QFz29Fg5jDuTPXVtey05BLm7OB+M8fnvE64RNegzX7U+5NUXcOcnpTIK0YfSHBg8gYd0oxIq3IZTe9SfPZiRw== dependencies: "@octokit/types" "^6.39.0" deprecation "^2.3.1" "@octokit/plugin-rest-endpoint-methods@^7.0.0": version "7.0.1" resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.0.1.tgz#f7ebe18144fd89460f98f35a587b056646e84502" integrity sha512-pnCaLwZBudK5xCdrR823xHGNgqOzRnJ/mpC/76YPpNP7DybdsJtP7mdOwh+wYZxK5jqeQuhu59ogMI4NRlBUvA== dependencies: "@octokit/types" "^9.0.0" deprecation "^2.3.1" "@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0": version "2.1.0" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677" integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg== dependencies: "@octokit/types" "^6.0.3" deprecation "^2.0.0" once "^1.4.0" "@octokit/request-error@^3.0.0": version "3.0.2" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-3.0.2.tgz#f74c0f163d19463b87528efe877216c41d6deb0a" integrity sha512-WMNOFYrSaX8zXWoJg9u/pKgWPo94JXilMLb2VManNOby9EZxrQaBe/QSC4a1TzpAlpxofg2X/jMnCyZgL6y7eg== dependencies: "@octokit/types" "^8.0.0" deprecation "^2.0.0" once "^1.4.0" "@octokit/request@^5.4.14", "@octokit/request@^5.6.0", "@octokit/request@^5.6.3": version "5.6.3" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0" integrity sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A== dependencies: "@octokit/endpoint" "^6.0.1" "@octokit/request-error" "^2.1.0" "@octokit/types" "^6.16.1" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/request@^6.0.0": version "6.2.2" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.2.tgz#a2ba5ac22bddd5dcb3f539b618faa05115c5a255" integrity sha512-6VDqgj0HMc2FUX2awIs+sM6OwLgwHvAi4KCK3mT2H2IKRt6oH9d0fej5LluF5mck1lRR/rFWN0YIDSYXYSylbw== dependencies: "@octokit/endpoint" "^7.0.0" "@octokit/request-error" "^3.0.0" "@octokit/types" "^8.0.0" is-plain-object "^5.0.0" node-fetch "^2.6.7" universal-user-agent "^6.0.0" "@octokit/rest@^18.12.0": version "18.12.0" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881" integrity sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q== dependencies: "@octokit/core" "^3.5.1" "@octokit/plugin-paginate-rest" "^2.16.8" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^5.12.0" "@octokit/rest@^19.0.7": version "19.0.7" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.7.tgz#d2e21b4995ab96ae5bfae50b4969da7e04e0bb70" integrity sha512-HRtSfjrWmWVNp2uAkEpQnuGMJsu/+dBr47dRc5QVgsCbnIc1+GFEaoKBWkYG+zjrsHpSqcAElMio+n10c0b5JA== dependencies: "@octokit/core" "^4.1.0" "@octokit/plugin-paginate-rest" "^6.0.0" "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^7.0.0" "@octokit/types@^5.0.0": version "5.2.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-5.2.0.tgz#d075dc23bf293f540739250b6879e2c1be2fc20c" integrity sha512-XjOk9y4m8xTLIKPe1NFxNWBdzA2/z3PFFA/bwf4EoH6oS8hM0Y46mEa4Cb+KCyj/tFDznJFahzQ0Aj3o1FYq4A== dependencies: "@types/node" ">= 8" "@octokit/types@^6.0.3", "@octokit/types@^6.10.0", "@octokit/types@^6.12.2", "@octokit/types@^6.16.1", "@octokit/types@^6.39.0", "@octokit/types@^6.40.0": version "6.41.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.41.0.tgz#e58ef78d78596d2fb7df9c6259802464b5f84a04" integrity sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg== dependencies: "@octokit/openapi-types" "^12.11.0" "@octokit/types@^8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-8.0.0.tgz#93f0b865786c4153f0f6924da067fe0bb7426a9f" integrity sha512-65/TPpOJP1i3K4lBJMnWqPUJ6zuOtzhtagDvydAWbEXpbFYA0oMKKyLb95NFZZP0lSh/4b6K+DQlzvYQJQQePg== dependencies: "@octokit/openapi-types" "^14.0.0" "@octokit/types@^9.0.0": version "9.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-9.0.0.tgz#6050db04ddf4188ec92d60e4da1a2ce0633ff635" integrity sha512-LUewfj94xCMH2rbD5YJ+6AQ4AVjFYTgpp6rboWM5T7N3IsIF65SBEOVcYMGAEzO/kKNiNaW4LoWtoThOhH06gw== dependencies: "@octokit/openapi-types" "^16.0.0" "@opentelemetry/api@^1.0.1": version "1.0.4" resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.0.4.tgz#a167e46c10d05a07ab299fc518793b0cff8f6924" integrity sha512-BuJuXRSJNQ3QoKA6GWWDyuLpOUck+9hAXNMCnrloc1aWVoy6Xq6t9PUV08aBZ4Lutqq2LEHM486bpZqoViScog== "@primer/octicons@^10.0.0": version "10.0.0" resolved "https://registry.yarnpkg.com/@primer/octicons/-/octicons-10.0.0.tgz#81e94ed32545dfd3472c8625a5b345f3ea4c153d" integrity sha512-iuQubq62zXZjPmaqrsfsCZUqIJgZhmA6W0tKzIKGRbkoLnff4TFFCL87hfIRATZ5qZPM4m8ioT8/bXI7WVa9WQ== dependencies: object-assign "^4.1.1" "@sindresorhus/is@^4.0.0": version "4.6.0" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" integrity sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw== "@szmarczak/http-timer@^4.0.5": version "4.0.6" resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-4.0.6.tgz#b4a914bb62e7c272d4e5989fe4440f812ab1d807" integrity sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w== dependencies: defer-to-connect "^2.0.0" "@types/basic-auth@^1.1.3": version "1.1.3" resolved "https://registry.yarnpkg.com/@types/basic-auth/-/basic-auth-1.1.3.tgz#a787ede8310804174fbbf3d6c623ab1ccedb02cd" integrity sha512-W3rv6J0IGlxqgE2eQ2pTb0gBjaGtejQpJ6uaCjz3UQ65+TFTPC5/lAE+POfx1YLdjtxvejJzsIAfd3MxWiVmfg== dependencies: "@types/node" "*" "@types/body-parser@*": version "1.19.0" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.0.tgz#0685b3c47eb3006ffed117cdd55164b61f80538f" integrity sha512-W98JrE0j2K78swW4ukqMleo8R7h/pFETjM2DQ90MF6XK2i4LO4W3gQ71Lt4w3bfm2EvVSyWHplECvB5sK22yFQ== dependencies: "@types/connect" "*" "@types/node" "*" "@types/btoa-lite@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/btoa-lite/-/btoa-lite-1.0.0.tgz#e190a5a548e0b348adb0df9ac7fa5f1151c7cca4" integrity sha512-wJsiX1tosQ+J5+bY5LrSahHxr2wT+uME5UDwdN1kg4frt40euqA+wzECkmq4t5QbveHiJepfdThgQrPw6KiSlg== "@types/busboy@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@types/busboy/-/busboy-1.5.0.tgz#62681556cbbd2afc8d2efa6bafaa15602f0838b9" integrity sha512-ncOOhwmyFDW76c/Tuvv9MA9VGYUCn8blzyWmzYELcNGDb0WXWLSmFi7hJq25YdRBYJrmMBB5jZZwUjlJe9HCjQ== dependencies: "@types/node" "*" "@types/cacheable-request@^6.0.1": version "6.0.2" resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.2.tgz#c324da0197de0a98a2312156536ae262429ff6b9" integrity sha512-B3xVo+dlKM6nnKTcmm5ZtY/OL8bOAOd2Olee9M1zft65ox50OzjEHW91sDiU9j6cvW8Ejg1/Qkf4xd2kugApUA== dependencies: "@types/http-cache-semantics" "*" "@types/keyv" "*" "@types/node" "*" "@types/responselike" "*" "@types/chai-as-promised@*": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.1.tgz#004c27a4ac640e9590e25d8b0980cb0a6609bfd8" integrity sha512-dberBxQW/XWv6BMj0su1lV9/C9AUx5Hqu2pisuS6S4YK/Qt6vurcj/BmcbEsobIWWCQzhesNY8k73kIxx4X7Mg== dependencies: "@types/chai" "*" "@types/chai-as-promised@^7.1.3": version "7.1.3" resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-7.1.3.tgz#779166b90fda611963a3adbfd00b339d03b747bd" integrity sha512-FQnh1ohPXJELpKhzjuDkPLR2BZCAqed+a6xV4MI/T3XzHfd2FlarfUGUdZYgqYe8oxkYn0fchHEeHfHqdZ96sg== dependencies: "@types/chai" "*" "@types/chai@*": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.1.7.tgz#1b8e33b61a8c09cbe1f85133071baa0dbf9fa71a" integrity sha512-2Y8uPt0/jwjhQ6EiluT0XCri1Dbplr0ZxfFXUz+ye13gaqE8u5gL5ppao1JrUYr9cIip5S6MvQzBS7Kke7U9VA== "@types/chai@^4.2.12": version "4.2.12" resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.2.12.tgz#6160ae454cd89dae05adc3bb97997f488b608201" integrity sha512-aN5IAC8QNtSUdQzxu7lGBgYAOuU1tmRU4c9dIq5OKGf/SBVjXo+ffM2wEjudAWbgpOhy60nLoAGH1xm8fpCKFQ== "@types/color-name@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== "@types/concat-stream@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/concat-stream/-/concat-stream-1.6.1.tgz#24bcfc101ecf68e886aaedce60dfd74b632a1b74" integrity sha512-eHE4cQPoj6ngxBZMvVf6Hw7Mh4jMW4U9lpGmS5GBPB9RYxlFg+CHaVN7ErNY4W9XfLIEn20b4VDYaIrbq0q4uA== dependencies: "@types/node" "*" "@types/connect@*": version "3.4.33" resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.33.tgz#31610c901eca573b8713c3330abc6e6b9f588546" integrity sha512-2+FrkXY4zllzTNfJth7jOqEHC+enpLeGslEhpnTAkg21GkRrWV4SsAtqchtT4YS9/nODBU2/ZfsBY2X4J/dX7A== dependencies: "@types/node" "*" "@types/debug@^4.0.0": version "4.1.7" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82" integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg== dependencies: "@types/ms" "*" "@types/dirty-chai@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@types/dirty-chai/-/dirty-chai-2.0.2.tgz#eeac4802329a41ed7815ac0c1a6360335bf77d0c" integrity sha512-BruwIN/UQEU0ePghxEX+OyjngpOfOUKJQh3cmfeq2h2Su/g001iljVi3+Y2y2EFp3IPgjf4sMrRU33Hxv1FUqw== dependencies: "@types/chai" "*" "@types/chai-as-promised" "*" "@types/eslint-scope@^3.7.3": version "3.7.4" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.4.tgz#37fc1223f0786c39627068a12e94d6e6fc61de16" integrity sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA== dependencies: "@types/eslint" "*" "@types/estree" "*" "@types/eslint@*": version "8.4.5" resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.4.5.tgz#acdfb7dd36b91cc5d812d7c093811a8f3d9b31e4" integrity sha512-dhsC09y1gpJWnK+Ff4SGvCuSnk9DaU0BJZSzOwa6GVSg65XtTugLBITDAAzRU5duGBoXBHpdR/9jHGxJjNflJQ== dependencies: "@types/estree" "*" "@types/json-schema" "*" "@types/estree@*": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.0.tgz#5fb2e536c1ae9bf35366eed879e827fa59ca41c2" integrity sha512-WulqXMDUTYAXCjZnk6JtIHPigp55cVtDgDrO2gHRwhyJto21+1zbVCtOYB2L1F9w4qCQ0rOGWBnBe0FNTiEJIQ== "@types/estree@^0.0.51": version "0.0.51" resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== "@types/events@*": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/events/-/events-3.0.0.tgz#2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7" integrity sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g== "@types/express-serve-static-core@^4.17.18": version "4.17.28" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.28.tgz#c47def9f34ec81dc6328d0b1b5303d1ec98d86b8" integrity sha512-P1BJAEAW3E2DJUlkgq4tOL3RyMunoWXqbSCygWo5ZIWTjUgN1YnaXWW4VWl/oc8vs/XoYibEGBKP0uZyF4AHig== dependencies: "@types/node" "*" "@types/qs" "*" "@types/range-parser" "*" "@types/express@^4.17.13": version "4.17.13" resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.13.tgz#a76e2995728999bab51a33fabce1d705a3709034" integrity sha512-6bSZTPaTIACxn48l50SR+axgrqm6qXFIxrdAKaG6PaJk3+zuUr35hBlgT7vOmJcum+OEaIBLtHV/qloEAFITeA== dependencies: "@types/body-parser" "*" "@types/express-serve-static-core" "^4.17.18" "@types/qs" "*" "@types/serve-static" "*" "@types/fs-extra@^9.0.1": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.1.tgz#91c8fc4c51f6d5dbe44c2ca9ab09310bd00c7918" integrity sha512-B42Sxuaz09MhC3DDeW5kubRcQ5by4iuVQ0cRRWM2lggLzAa/KVom0Aft/208NgMvNQQZ86s5rVcqDdn/SH0/mg== dependencies: "@types/node" "*" "@types/glob@^7.1.1": version "7.1.1" resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.1.1.tgz#aa59a1c6e3fbc421e07ccd31a944c30eba521575" integrity sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w== dependencies: "@types/events" "*" "@types/minimatch" "*" "@types/node" "*" "@types/http-cache-semantics@*": version "4.0.1" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ== "@types/is-empty@^1.0.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/is-empty/-/is-empty-1.2.0.tgz#16bc578060c9b0b6953339eea906c255a375bf86" integrity sha512-brJKf2boFhUxTDxlpI7cstwiUtA2ovm38UzFTi9aZI6//ARncaV+Q5ALjCaJqXaMtdZk/oPTJnSutugsZR6h8A== "@types/js-yaml@^4.0.0": version "4.0.2" resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-4.0.2.tgz#4117a7a378593a218e9d6f0ef44ce6d5d9edf7fa" integrity sha512-KbeHS/Y4R+k+5sWXEYzAZKuB1yQlZtEghuhRxrVRLaqhtoG5+26JwQsa4HyS3AWX8v1Uwukma5HheduUDskasA== "@types/json-buffer@~3.0.0": version "3.0.0" resolved "https://registry.yarnpkg.com/@types/json-buffer/-/json-buffer-3.0.0.tgz#85c1ff0f0948fc159810d4b5be35bf8c20875f64" integrity sha512-3YP80IxxFJB4b5tYC2SUPwkg0XQLiu0nWvhRgEatgjf+29IcWO9X1k8xRv5DGssJ/lCrjYTjQPcobJr2yWIVuQ== "@types/json-schema@*", "@types/json-schema@^7.0.8": version "7.0.11" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== "@types/json-schema@^7.0.3": version "7.0.3" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.3.tgz#bdfd69d61e464dcc81b25159c270d75a73c1a636" integrity sha512-Il2DtDVRGDcqjDtE+rF8iqg1CArehSK84HZJCT7AMITlyXRBpuPhqGLDQMowraqqu1coEaimg4ZOqggt6L6L+A== "@types/json-schema@^7.0.4": version "7.0.4" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339" integrity sha512-8+KAKzEvSUdeo+kmqnKrqgeE+LcA0tjYWFY7RPProVYwnqDjukzO+3b6dLD56rYX5TdWejnEOLJYOIeh4CXKuA== "@types/json5@^0.0.29": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= "@types/jsonwebtoken@^9.0.0": version "9.0.1" resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-9.0.1.tgz#29b1369c4774200d6d6f63135bf3d1ba3ef997a4" integrity sha512-c5ltxazpWabia/4UzhIoaDcIza4KViOQhdbjRlfcIGVnsE3c3brkz9Z+F/EeJIECOQP7W7US2hNE930cWWkPiw== dependencies: "@types/node" "*" "@types/keyv@*": version "3.1.4" resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.4.tgz#3ccdb1c6751b0c7e52300bcdacd5bcbf8faa75b6" integrity sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg== dependencies: "@types/node" "*" "@types/klaw@^3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@types/klaw/-/klaw-3.0.1.tgz#29f90021c0234976aa4eb97efced9cb6db9fa8b3" integrity sha512-acnF3n9mYOr1aFJKFyvfNX0am9EtPUsYPq22QUCGdJE+MVt6UyAN1jwo+PmOPqXD4K7ZS9MtxDEp/un0lxFccA== dependencies: "@types/node" "*" "@types/linkify-it@*": version "2.1.0" resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-2.1.0.tgz#ea3dd64c4805597311790b61e872cbd1ed2cd806" integrity sha512-Q7DYAOi9O/+cLLhdaSvKdaumWyHbm7HAk/bFwwyTuU0arR5yyCeW5GOoqt4tJTpDRxhpx9Q8kQL6vMpuw9hDSw== "@types/lru-cache@^5.1.0": version "5.1.0" resolved "https://registry.yarnpkg.com/@types/lru-cache/-/lru-cache-5.1.0.tgz#57f228f2b80c046b4a1bd5cac031f81f207f4f03" integrity sha512-RaE0B+14ToE4l6UqdarKPnXwVDuigfFv+5j9Dze/Nqr23yyuqdNvzcZi3xB+3Agvi5R4EOgAksfv3lXX4vBt9w== "@types/markdown-it@^12.0.0": version "12.2.3" resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-12.2.3.tgz#0d6f6e5e413f8daaa26522904597be3d6cd93b51" integrity sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ== dependencies: "@types/linkify-it" "*" "@types/mdurl" "*" "@types/mdast@^3.0.0": version "3.0.7" resolved "https://registry.yarnpkg.com/@types/mdast/-/mdast-3.0.7.tgz#cba63d0cc11eb1605cea5c0ad76e02684394166b" integrity sha512-YwR7OK8aPmaBvMMUi+pZXBNoW2unbVbfok4YRqGMJBe1dpDlzpRkJrYEYmvjxgs5JhuQmKfDexrN98u941Zasg== dependencies: "@types/unist" "*" "@types/mdurl@*": version "1.0.2" resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-1.0.2.tgz#e2ce9d83a613bacf284c7be7d491945e39e1f8e9" integrity sha512-eC4U9MlIcu2q0KQmXszyn5Akca/0jrQmwDRgpAMJai7qBWq4amIQhZyNau4VYGtCeALvW1/NtjzJJ567aZxfKA== "@types/mime@*": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-2.0.1.tgz#dc488842312a7f075149312905b5e3c0b054c79d" integrity sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw== "@types/mime@^1": version "1.3.2" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a" integrity sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw== "@types/minimatch@*": version "3.0.3" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.3.tgz#3dca0e3f33b200fc7d1139c0cd96c1268cadfd9d" integrity sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA== "@types/minimist@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= "@types/mocha@^7.0.2": version "7.0.2" resolved "https://registry.yarnpkg.com/@types/mocha/-/mocha-7.0.2.tgz#b17f16cf933597e10d6d78eae3251e692ce8b0ce" integrity sha512-ZvO2tAcjmMi8V/5Z3JsyofMe3hasRcaw88cto5etSVMwVQfeivGAlEYmaQgceUSVYFofVjT+ioHsATjdWcFt1w== "@types/ms@*": version "0.7.31" resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197" integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA== "@types/node-fetch@^2.5.0": version "2.6.1" resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.1.tgz#8f127c50481db65886800ef496f20bbf15518975" integrity sha512-oMqjURCaxoSIsHSr1E47QHzbmzNR5rK8McHuNb11BOM9cHcIK3Avy0s/b2JlXHoQGTYS3NsvWzV1M0iK7l0wbA== dependencies: "@types/node" "*" form-data "^3.0.0" "@types/node@*": version "12.6.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.1.tgz#d5544f6de0aae03eefbb63d5120f6c8be0691946" integrity sha512-rp7La3m845mSESCgsJePNL/JQyhkOJA6G4vcwvVgkDAwHhGdq5GCumxmPjEk1MZf+8p5ZQAUE7tqgQRQTXN7uQ== "@types/node@>= 8": version "14.0.27" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.27.tgz#a151873af5a5e851b51b3b065c9e63390a9e0eb1" integrity sha512-kVrqXhbclHNHGu9ztnAwSncIgJv/FaxmzXJvGXNdcCpV1b8u1/Mi6z6m0vwy0LzKeXFTPLH0NzwmoJ3fNCIq0g== "@types/node@^11.13.7": version "11.13.22" resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.22.tgz#91ee88ebfa25072433497f6f3150f84fa8c3a91b" integrity sha512-rOsaPRUGTOXbRBOKToy4cgZXY4Y+QSVhxcLwdEveozbk7yuudhWMpxxcaXqYizLMP3VY7OcWCFtx9lGFh5j5kg== "@types/node@^16.0.0": version "16.4.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d" integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg== "@types/node@^18.11.18": version "18.11.18" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.18.tgz#8dfb97f0da23c2293e554c5a50d61ef134d7697f" integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA== "@types/parse-json@^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== "@types/qs@*": version "6.9.3" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" integrity sha512-7s9EQWupR1fTc2pSMtXRQ9w9gLOcrJn+h7HOXw4evxyvVqMi4f+q7d2tnFe3ng3SNHjtK+0EzGMGFUQX4/AQRA== "@types/range-parser@*": version "1.2.3" resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.3.tgz#7ee330ba7caafb98090bece86a5ee44115904c2c" integrity sha512-ewFXqrQHlFsgc09MK5jP5iR7vumV/BYayNC6PgJO2LPe8vrnNFyjQjSppfEngITi0qvfKtzFvgKymGheFM9UOA== "@types/repeat-string@^1.0.0": version "1.6.1" resolved "https://registry.yarnpkg.com/@types/repeat-string/-/repeat-string-1.6.1.tgz#8bb5686e662ce1d962271b0b043623bf51404cdc" integrity sha512-vdna8kjLGljgtPnYN6MBD2UwX62QE0EFLj9QlLXvg6dEu66NksXB900BNguBCMZZY2D9SSqncUskM23vT3uvWQ== "@types/responselike@*", "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA== dependencies: "@types/node" "*" "@types/semver@^7.3.3": version "7.3.3" resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.3.tgz#3ad6ed949e7487e7bda6f886b4a2434a2c3d7b1a" integrity sha512-jQxClWFzv9IXdLdhSaTf16XI3NYe6zrEbckSpb5xhKfPbWgIyAY0AFyWWWfaiDcBuj3UHmMkCIwSRqpKMTZL2Q== "@types/send@^0.14.5": version "0.14.5" resolved "https://registry.yarnpkg.com/@types/send/-/send-0.14.5.tgz#653f7d25b93c3f7f51a8994addaf8a229de022a7" integrity sha512-0mwoiK3DXXBu0GIfo+jBv4Wo5s1AcsxdpdwNUtflKm99VEMvmBPJ+/NBNRZy2R5JEYfWL/u4nAHuTUTA3wFecQ== dependencies: "@types/mime" "*" "@types/node" "*" "@types/serve-static@*": version "1.13.10" resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.13.10.tgz#f5e0ce8797d2d7cc5ebeda48a52c96c4fa47a8d9" integrity sha512-nCkHGI4w7ZgAdNkrEu0bv+4xNV/XDqW+DydknebMOQwkpDGx8G+HTlj7R7ABI8i8nKxVw0wtKPi1D+lPOkh4YQ== dependencies: "@types/mime" "^1" "@types/node" "*" "@types/split@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/split/-/split-1.0.0.tgz#24f7c35707450b002f203383228f5a2bc1e6c228" integrity sha512-pm9S1mkr+av0j7D6pFyqhBxXDbnbO9gqj4nb8DtGtCewvj0XhIv089SSwXrjrIizT1UquO8/h83hCut0pa3u8A== dependencies: "@types/node" "*" "@types/through" "*" "@types/stream-chain@*": version "2.0.0" resolved "https://registry.yarnpkg.com/@types/stream-chain/-/stream-chain-2.0.0.tgz#aed7fc21ac3686bc721aebbbd971f5a857e567e4" integrity sha512-O3IRJcZi4YddlS8jgasH87l+rdNmad9uPAMmMZCfRVhumbWMX6lkBWnIqr9kokO5sx8LHp8peQ1ELhMZHbR0Gg== dependencies: "@types/node" "*" "@types/stream-json@^1.5.1": version "1.5.1" resolved "https://registry.yarnpkg.com/@types/stream-json/-/stream-json-1.5.1.tgz#ae8d1133f9f920e18c6e94b233cb57d014a47b8d" integrity sha512-Blg6GJbKVEB1J/y/2Tv+WrYiMzPTIqyuZ+zWDJtAF8Mo8A2XQh/lkSX4EYiM+qtS+GY8ThdGi6gGA9h4sjvL+g== dependencies: "@types/node" "*" "@types/stream-chain" "*" "@types/supports-color@^8.0.0": version "8.1.1" resolved "https://registry.yarnpkg.com/@types/supports-color/-/supports-color-8.1.1.tgz#1b44b1b096479273adf7f93c75fc4ecc40a61ee4" integrity sha512-dPWnWsf+kzIG140B8z2w3fr5D03TLWbOAFQl45xUpI3vcizeXriNR5VYkWZ+WTMsUHqZ9Xlt3hrxGNANFyNQfw== "@types/temp@^0.8.34": version "0.8.34" resolved "https://registry.yarnpkg.com/@types/temp/-/temp-0.8.34.tgz#03e4b3cb67cbb48c425bbf54b12230fef85540ac" integrity sha512-oLa9c5LHXgS6UimpEVp08De7QvZ+Dfu5bMQuWyMhf92Z26Q10ubEMOWy9OEfUdzW7Y/sDWVHmUaLFtmnX/2j0w== dependencies: "@types/node" "*" "@types/text-table@^0.2.0": version "0.2.2" resolved "https://registry.yarnpkg.com/@types/text-table/-/text-table-0.2.2.tgz#774c90cfcfbc8b4b0ebb00fecbe861dc8b1e8e26" integrity sha512-dGoI5Af7To0R2XE8wJuc6vwlavWARsCh3UKJPjWs1YEqGUqfgBI/j/4GX0yf19/DsDPPf0YAXWAp8psNeIehLg== "@types/through@*": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/through/-/through-0.0.29.tgz#72943aac922e179339c651fa34a4428a4d722f93" integrity sha512-9a7C5VHh+1BKblaYiq+7Tfc+EOmjMdZaD1MYtkQjSoxgB69tBjW98ry6SKsi4zEIWztLOMRuL87A3bdT/Fc/4w== dependencies: "@types/node" "*" "@types/tunnel@^0.0.3": version "0.0.3" resolved "https://registry.yarnpkg.com/@types/tunnel/-/tunnel-0.0.3.tgz#f109e730b072b3136347561fc558c9358bb8c6e9" integrity sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA== dependencies: "@types/node" "*" "@types/unist@*", "@types/unist@^2.0.0": version "2.0.6" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.6.tgz#250a7b16c3b91f672a24552ec64678eeb1d3a08d" integrity sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ== "@types/unist@^2.0.2": version "2.0.3" resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e" integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ== "@types/uuid@^3.4.6": version "3.4.6" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.6.tgz#d2c4c48eb85a757bf2927f75f939942d521e3016" integrity sha512-cCdlC/1kGEZdEglzOieLDYBxHsvEOIg7kp/2FYyVR9Pxakq+Qf/inL3RKQ+PA8gOlI/NnL+fXmQH12nwcGzsHw== dependencies: "@types/node" "*" "@types/webpack-env@^1.17.0": version "1.17.0" resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.17.0.tgz#f99ce359f1bfd87da90cc4a57cab0a18f34a48d0" integrity sha512-eHSaNYEyxRA5IAG0Ym/yCyf86niZUIF/TpWKofQI/CVfh5HsMEUyfE2kwFxha4ow0s5g0LfISQxpDKjbRDrizw== "@types/webpack@^5.28.0": version "5.28.0" resolved "https://registry.yarnpkg.com/@types/webpack/-/webpack-5.28.0.tgz#78dde06212f038d77e54116cfe69e88ae9ed2c03" integrity sha512-8cP0CzcxUiFuA9xGJkfeVpqmWTk9nx6CWwamRGCj95ph1SmlRRk9KlCZ6avhCbZd4L68LvYT6l1kpdEnQXrF8w== dependencies: "@types/node" "*" tapable "^2.2.0" webpack "^5" "@types/yauzl@^2.9.1": version "2.10.0" resolved "https://registry.yarnpkg.com/@types/yauzl/-/yauzl-2.10.0.tgz#b3248295276cf8c6f153ebe6a9aba0c988cb2599" integrity sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw== dependencies: "@types/node" "*" "@typescript-eslint/eslint-plugin@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-4.4.1.tgz#b8acea0373bd2a388ac47df44652f00bf8b368f5" integrity sha512-O+8Utz8pb4OmcA+Nfi5THQnQpHSD2sDUNw9AxNHpuYOo326HZTtG8gsfT+EAYuVrFNaLyNb2QnUNkmTRDskuRA== dependencies: "@typescript-eslint/experimental-utils" "4.4.1" "@typescript-eslint/scope-manager" "4.4.1" debug "^4.1.1" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-4.4.1.tgz#40613b9757fa0170de3e0043254dbb077cafac0c" integrity sha512-Nt4EVlb1mqExW9cWhpV6pd1a3DkUbX9DeyYsdoeziKOpIJ04S2KMVDO+SEidsXRH/XHDpbzXykKcMTLdTXH6cQ== dependencies: "@types/json-schema" "^7.0.3" "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" eslint-scope "^5.0.0" eslint-utils "^2.0.0" "@typescript-eslint/parser@^4.4.1": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-4.4.1.tgz#25fde9c080611f303f2f33cedb145d2c59915b80" integrity sha512-S0fuX5lDku28Au9REYUsV+hdJpW/rNW0gWlc4SXzF/kdrRaAVX9YCxKpziH7djeWT/HFAjLZcnY7NJD8xTeUEg== dependencies: "@typescript-eslint/scope-manager" "4.4.1" "@typescript-eslint/types" "4.4.1" "@typescript-eslint/typescript-estree" "4.4.1" debug "^4.1.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-4.4.1.tgz#d19447e60db2ce9c425898d62fa03b2cce8ea3f9" integrity sha512-2oD/ZqD4Gj41UdFeWZxegH3cVEEH/Z6Bhr/XvwTtGv66737XkR4C9IqEkebCuqArqBJQSj4AgNHHiN1okzD/wQ== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-4.4.1.tgz#c507b35cf523bc7ba00aae5f75ee9b810cdabbc1" integrity sha512-KNDfH2bCyax5db+KKIZT4rfA8rEk5N0EJ8P0T5AJjo5xrV26UAzaiqoJCxeaibqc0c/IvZxp7v2g3difn2Pn3w== "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-4.4.1.tgz#598f6de488106c2587d47ca2462c60f6e2797cb8" integrity sha512-wP/V7ScKzgSdtcY1a0pZYBoCxrCstLrgRQ2O9MmCUZDtmgxCO/TCqOTGRVwpP4/2hVfqMz/Vw1ZYrG8cVxvN3g== dependencies: "@typescript-eslint/types" "4.4.1" "@typescript-eslint/visitor-keys" "4.4.1" debug "^4.1.1" globby "^11.0.1" is-glob "^4.0.1" lodash "^4.17.15" semver "^7.3.2" tsutils "^3.17.1" "@typescript-eslint/[email protected]": version "4.4.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-4.4.1.tgz#1769dc7a9e2d7d2cfd3318b77ed8249187aed5c3" integrity sha512-H2JMWhLaJNeaylSnMSQFEhT/S/FsJbebQALmoJxMPMxLtlVAMy2uJP/Z543n9IizhjRayLSqoInehCeNW9rWcw== dependencies: "@typescript-eslint/types" "4.4.1" eslint-visitor-keys "^2.0.0" "@vscode/l10n@^0.0.10": version "0.0.10" resolved "https://registry.yarnpkg.com/@vscode/l10n/-/l10n-0.0.10.tgz#9c513107c690c0dd16e3ec61e453743de15ebdb0" integrity sha512-E1OCmDcDWa0Ya7vtSjp/XfHFGqYJfh+YPC1RkATU71fTac+j1JjCcB3qwSzmlKAighx2WxhLlfhS0RwAN++PFQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" integrity sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw== dependencies: "@webassemblyjs/helper-numbers" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz#f6c61a705f0fd7a6aecaa4e8198f23d9dc179e4f" integrity sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz#1a63192d8788e5c012800ba6a7a46c705288fd16" integrity sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz#832a900eb444884cde9a7cad467f81500f5e5ab5" integrity sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz#64d81da219fbbba1e3bd1bfc74f6e8c4e10a62ae" integrity sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ== dependencies: "@webassemblyjs/floating-point-hex-parser" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz#f328241e41e7b199d0b20c18e88429c4433295e1" integrity sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz#21ee065a7b635f319e738f0dd73bfbda281c097a" integrity sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz#963929e9bbd05709e7e12243a099180812992614" integrity sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ== dependencies: "@xtuc/ieee754" "^1.2.0" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.11.1.tgz#ce814b45574e93d76bae1fb2644ab9cdd9527aa5" integrity sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw== dependencies: "@xtuc/long" "4.2.2" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.11.1.tgz#d1f8b764369e7c6e6bae350e854dec9a59f0a3ff" integrity sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ== "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz#ad206ebf4bf95a058ce9880a8c092c5dec8193d6" integrity sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/helper-wasm-section" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-opt" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/wast-printer" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz#86c5ea304849759b7d88c47a32f4f039ae3c8f76" integrity sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz#657b4c2202f4cf3b345f8a4c6461c8c2418985f2" integrity sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-buffer" "1.11.1" "@webassemblyjs/wasm-gen" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz#86ca734534f417e9bd3c67c7a1c75d8be41fb199" integrity sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA== dependencies: "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/helper-api-error" "1.11.1" "@webassemblyjs/helper-wasm-bytecode" "1.11.1" "@webassemblyjs/ieee754" "1.11.1" "@webassemblyjs/leb128" "1.11.1" "@webassemblyjs/utf8" "1.11.1" "@webassemblyjs/[email protected]": version "1.11.1" resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz#d0c73beda8eec5426f10ae8ef55cee5e7084c2f0" integrity sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg== dependencies: "@webassemblyjs/ast" "1.11.1" "@xtuc/long" "4.2.2" "@webpack-cli/configtest@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== "@webpack-cli/info@^1.5.0": version "1.5.0" resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== dependencies: envinfo "^7.7.3" "@webpack-cli/serve@^1.7.0": version "1.7.0" resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== "@xtuc/ieee754@^1.2.0": version "1.2.0" resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== "@xtuc/[email protected]": version "4.2.2" resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== accepts@~1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e" integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw== dependencies: mime-types "~2.1.34" negotiator "0.6.3" acorn-import-assertions@^1.7.6: version "1.8.0" resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz#ba2b5939ce62c238db6d93d81c9b111b29b855e9" integrity sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw== acorn-jsx@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.2.0.tgz#4c66069173d6fdd68ed85239fc256226182b2ebe" integrity sha512-HiUX/+K2YpkpJ+SzBffkM/AQ2YE03S0U1kjTLVpoJdhZMOWy8qvXVN9JdLqv2QsaQ6MPYQIuNmwD8zOiYUofLQ== acorn@^7.1.1, acorn@^7.2.0: version "7.3.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.3.1.tgz#85010754db53c3fbaf3b9ea3e083aa5c5d147ffd" integrity sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA== acorn@^8.4.1, acorn@^8.5.0: version "8.7.1" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.7.1.tgz#0197122c843d1bf6d0a5e83220a788f278f63c30" integrity sha512-Xx54uLJQZ19lKygFXOWsscKUbsBZW0CPykPhVQdhIeIwrbPmJzqeASDInc8nKBnp/JT6igTs82qPXz069H8I/A== aggregate-error@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.0.1.tgz#db2fe7246e536f40d9b5442a39e117d7dd6a24e0" integrity sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA== dependencies: clean-stack "^2.0.0" indent-string "^4.0.0" ajv-keywords@^3.4.1: version "3.4.1" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== ajv-keywords@^3.5.2: version "3.5.2" resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d" integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== ajv@^6.10.0, ajv@^6.10.2, ajv@^6.12.2, ajv@^6.12.5: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== dependencies: fast-deep-equal "^3.1.1" fast-json-stable-stringify "^2.0.0" json-schema-traverse "^0.4.1" uri-js "^4.2.2" ansi-colors@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: version "4.3.1" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.1.tgz#a5c47cc43181f1f38ffd7076837700d395522a61" integrity sha512-JWF7ocqNrp8u9oqpgV+wH5ftbt+cfvv+PTjOvKLT3AdYly/LmORARfEVT1iyjwN+4MqE5UmVKoAdIBqeoCHgLA== dependencies: type-fest "^0.11.0" ansi-regex@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-4.1.1.tgz#164daac87ab2d6f6db3a29875e2d1766582dabed" integrity sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g== ansi-regex@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== ansi-regex@^6.0.0: version "6.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" ansi-styles@^4.0.0, ansi-styles@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.2.1.tgz#90ae75c424d008d2624c5bf29ead3177ebfcf359" integrity sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA== dependencies: "@types/color-name" "^1.1.1" color-convert "^2.0.1" anymatch@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.0.3.tgz#2fb624fe0e84bccab00afee3d0006ed310f22f09" integrity sha512-c6IvoeBECQlMVuYUjSwimnhmztImpErfxJzWZhIQinIvQWoGOnB0dLIgifbPHQt5heS6mNlaZG16f06H3C8t1g== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== dependencies: sprintf-js "~1.0.2" argparse@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" integrity sha1-ml9pkFGx5wczKPKgCJaLZOopVdI= array-includes@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.0.3.tgz#184b48f62d92d7452bb31b323165c7f8bd02266d" integrity sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0= dependencies: define-properties "^1.1.2" es-abstract "^1.7.0" array-includes@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.1.tgz#cdd67e6852bdf9c1215460786732255ed2459348" integrity sha512-c2VXaCHl7zPsvpkFsw4nxvFie4fh1ur9bpcgsVkIjqn0H/Xwdg+7fv3n2r/isyS8EBj5b06M9kHyZuIr4El6WQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0" is-string "^1.0.5" array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= array.prototype.flat@^1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz#0de82b426b0318dbfdb940089e38b043d37f6c7b" integrity sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" arrify@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= assertion-error@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b" integrity sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw== astral-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-1.0.0.tgz#6c8c3fb827dd43ee3918f27b82782ab7658a6fd9" integrity sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg== astral-regex@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== async@^3.2.0: version "3.2.4" resolved "https://registry.yarnpkg.com/async/-/async-3.2.4.tgz#2d22e00f8cddeb5fde5dd33522b56d1cf569a81c" integrity sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ== asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= at-least-node@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== aws-sdk@^2.814.0: version "2.814.0" resolved "https://registry.yarnpkg.com/aws-sdk/-/aws-sdk-2.814.0.tgz#7a1c36006e0b5826f14bd2511b1d229ef6814bb0" integrity sha512-empd1m/J/MAkL6d9OeRpmg9thobULu0wk4v8W3JToaxGi2TD7PIdvE6yliZKyOVAdJINhBWEBhxR4OUIHhcGbQ== dependencies: buffer "4.9.2" events "1.1.1" ieee754 "1.1.13" jmespath "0.15.0" querystring "0.2.0" sax "1.2.1" url "0.10.3" uuid "3.3.2" xml2js "0.4.19" bail@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/bail/-/bail-2.0.1.tgz#d676736373a374058a935aec81b94c12ba815771" integrity sha512-d5FoTAr2S5DSUPKl85WNm2yUwsINN8eidIdIwsOge2t33DaOfOdSmmsI11jMN3GmALCXaw+Y6HMVHDzePshFAA== balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== base64-js@^1.0.2: version "1.3.0" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.3.0.tgz#cab1e6118f051095e58b5281aea8c1cd22bfc0e3" integrity sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw== base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== before-after-hook@^2.2.0: version "2.2.3" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.3.tgz#c51e809c81a4e354084422b9b26bad88249c517c" integrity sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ== big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" integrity sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ== binary-extensions@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.1.0.tgz#30fa40c9e7fe07dbc895678cd287024dea241dd9" integrity sha512-1Yj8h9Q+QDF5FzhMs/c9+6UntbD5MkRfRwac8DoEm9ZfUBZ7tZ55YcGVAzEe4bXsdQHEk+s9S5wsOKVdZrw0tQ== [email protected]: version "1.20.1" resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.1.tgz#b1812a8912c195cd371a3ee5e66faa2338a5c668" integrity sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw== dependencies: bytes "3.1.2" content-type "~1.0.4" debug "2.6.9" depd "2.0.0" destroy "1.2.0" http-errors "2.0.0" iconv-lite "0.4.24" on-finished "2.4.1" qs "6.11.0" raw-body "2.5.1" type-is "~1.6.18" unpipe "1.0.0" boolean@^3.0.1: version "3.2.0" resolved "https://registry.yarnpkg.com/boolean/-/boolean-3.2.0.tgz#9e5294af4e98314494cbb17979fa54ca159f116b" integrity sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" brace-expansion@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" braces@^3.0.1, braces@~3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== dependencies: fill-range "^7.0.1" browserslist@^4.14.5: version "4.21.2" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.2.tgz#59a400757465535954946a400b841ed37e2b4ecf" integrity sha512-MonuOgAtUB46uP5CezYbRaYKBNt2LxP0yX+Pmj4LkcDFGkn9Cbpi83d9sCjwQDErXsIJSzY5oKGDbgOlF/LPAA== dependencies: caniuse-lite "^1.0.30001366" electron-to-chromium "^1.4.188" node-releases "^2.0.6" update-browserslist-db "^1.0.4" btoa-lite@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/btoa-lite/-/btoa-lite-1.0.0.tgz#337766da15801210fdd956c22e9c6891ab9d0337" integrity sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA== buffer-crc32@~0.2.3: version "0.2.13" resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242" integrity sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ== [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz#f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819" integrity sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk= buffer-from@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== buffer-from@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== [email protected]: version "4.9.2" resolved "https://registry.yarnpkg.com/buffer/-/buffer-4.9.2.tgz#230ead344002988644841ab0244af8c44bbe3ef8" integrity sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg== dependencies: base64-js "^1.0.2" ieee754 "^1.1.4" isarray "^1.0.0" buffer@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== dependencies: base64-js "^1.3.1" ieee754 "^1.2.1" builtins@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/builtins/-/builtins-4.0.0.tgz#a8345420de82068fdc4d6559d0456403a8fb1905" integrity sha512-qC0E2Dxgou1IHhvJSLwGDSTvokbRovU5zZFuDY6oY8Y2lF3nGt5Ad8YZK7GMtqzY84Wu7pXTPeHQeHcXSXsRhw== dependencies: semver "^7.0.0" [email protected]: version "3.1.2" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5" integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg== cacheable-lookup@^5.0.3: version "5.0.4" resolved "https://registry.yarnpkg.com/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz#5a6b865b2c44357be3d5ebc2a467b032719a7005" integrity sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA== cacheable-request@^7.0.2: version "7.0.2" resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-7.0.2.tgz#ea0d0b889364a25854757301ca12b2da77f91d27" integrity sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew== dependencies: clone-response "^1.0.2" get-stream "^5.1.0" http-cache-semantics "^4.0.0" keyv "^4.0.0" lowercase-keys "^2.0.0" normalize-url "^6.0.1" responselike "^2.0.0" call-bind@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== dependencies: function-bind "^1.1.1" get-intrinsic "^1.0.2" callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== camelcase@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.2.0.tgz#924af881c9d525ac9d87f40d964e5cea982a1809" integrity sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg== caniuse-lite@^1.0.30001366: version "1.0.30001367" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001367.tgz#2b97fe472e8fa29c78c5970615d7cd2ee414108a" integrity sha512-XDgbeOHfifWV3GEES2B8rtsrADx4Jf+juKX2SICJcaUhjYBO3bR96kvEIHa15VU6ohtOhBZuPGGYGbXMRn0NCw== chai@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/chai/-/chai-4.2.0.tgz#760aa72cf20e3795e84b12877ce0e83737aa29e5" integrity sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw== dependencies: assertion-error "^1.1.0" check-error "^1.0.2" deep-eql "^3.0.1" get-func-name "^2.0.0" pathval "^1.1.0" type-detect "^4.0.5" chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" chalk@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-3.0.0.tgz#3f73c2bf526591f574cc492c51e2456349f844e4" integrity sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" chalk@^4.0.0, chalk@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== dependencies: ansi-styles "^4.1.0" supports-color "^7.1.0" character-entities-legacy@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz#57f4d00974c696e8f74e9f493e7fcb75b44d7ee7" integrity sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA== character-entities@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-entities/-/character-entities-2.0.0.tgz#508355fcc8c73893e0909efc1a44d28da2b6fdf3" integrity sha512-oHqMj3eAuJ77/P5PaIRcqk+C3hdfNwyCD2DAUcD5gyXkegAuF2USC40CEqPscDk4I8FRGMTojGJQkXDsN5QlJA== character-reference-invalid@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/character-reference-invalid/-/character-reference-invalid-2.0.0.tgz#a0bdeb89c051fe7ed5d3158b2f06af06984f2813" integrity sha512-pE3Z15lLRxDzWJy7bBHBopRwfI20sbrMVLQTC7xsPglCHf4Wv1e167OgYAFP78co2XlhojDyAqA+IAJse27//g== chardet@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== check-error@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" integrity sha1-V00xLt2Iu13YkS6Sht1sCu1KrII= check-for-leaks@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/check-for-leaks/-/check-for-leaks-1.2.1.tgz#4ac108ee3f8e6b99f5ad36f6b98cba1d7f4816d0" integrity sha512-9OdOSRZY6N0w5JCdJpqsC5MkD6EPGYpHmhtf4l5nl3DRETDZshP6C1EGN/vVhHDTY6AsOK3NhdFfrMe3NWZl7g== dependencies: anymatch "^3.0.2" minimist "^1.2.0" parse-gitignore "^0.4.0" walk-sync "^0.3.2" chokidar@^3.0.0: version "3.5.2" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.2.tgz#dba3976fcadb016f66fd365021d91600d01c1e75" integrity sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ== dependencies: anymatch "~3.1.2" braces "~3.0.2" glob-parent "~5.1.2" is-binary-path "~2.1.0" is-glob "~4.0.1" normalize-path "~3.0.0" readdirp "~3.6.0" optionalDependencies: fsevents "~2.3.2" chownr@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== chrome-trace-event@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4" integrity sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ== dependencies: tslib "^1.9.0" chromium-pickle-js@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/chromium-pickle-js/-/chromium-pickle-js-0.2.0.tgz#04a106672c18b085ab774d983dfa3ea138f22205" integrity sha1-BKEGZywYsIWrd02YPfo+oTjyIgU= clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== cli-cursor@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" integrity sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU= dependencies: restore-cursor "^2.0.0" cli-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== dependencies: restore-cursor "^3.1.0" cli-spinners@^2.0.0, cli-spinners@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.2.0.tgz#e8b988d9206c692302d8ee834e7a85c0144d8f77" integrity sha512-tgU3fKwzYjiLEQgPMD9Jt+JjHVL9kW93FiIMX/l7rivvOD4/LL0Mf7gda3+4U2KJBloybwgj5KEoQgGRioMiKQ== [email protected], cli-truncate@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== dependencies: slice-ansi "^3.0.0" string-width "^4.2.0" cli-width@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" integrity sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw== clone-deep@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== dependencies: is-plain-object "^2.0.4" kind-of "^6.0.2" shallow-clone "^3.0.0" clone-response@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.2.tgz#d1dc973920314df67fbeb94223b4ee350239e96b" integrity sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws= dependencies: mimic-response "^1.0.0" clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4= [email protected]: version "3.1.0" resolved "https://registry.yarnpkg.com/co/-/co-3.1.0.tgz#4ea54ea5a08938153185e15210c68d9092bc1b78" integrity sha1-TqVOpaCJOBUxheFSEMaNkJK8G3g= color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" color-convert@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== dependencies: color-name "~1.1.4" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= color-name@~1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== colorette@^2.0.14: version "2.0.19" resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== [email protected]: version "1.4.0" resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== colors@^1.1.2: version "1.3.3" resolved "https://registry.yarnpkg.com/colors/-/colors-1.3.3.tgz#39e005d546afe01e01f9c4ca8fa50f686a01205d" integrity sha512-mmGt/1pZqYRjMxB1axhTo16/snVZ5krrKkcmMeVKxzECMMXoCgnvTPp10QgHfcbQZw8Dq2jMNG6je4JlWU0gWg== combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== dependencies: delayed-stream "~1.0.0" commander@^2.20.0, commander@^2.9.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== commander@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== commander@^5.0.0, commander@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/commander/-/commander-5.1.0.tgz#46abbd1652f8e059bddaef99bbdcb2ad9cf179ae" integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg== commander@^7.0.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== commander@~9.4.1: version "9.4.1" resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.1.tgz#d1dd8f2ce6faf93147295c0df13c7c21141cfbdd" integrity sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw== compress-brotli@^1.3.8: version "1.3.8" resolved "https://registry.yarnpkg.com/compress-brotli/-/compress-brotli-1.3.8.tgz#0c0a60c97a989145314ec381e84e26682e7b38db" integrity sha512-lVcQsjhxhIXsuupfy9fmZUFtAIdBmXA7EGY6GBdgZ++qkM9zG4YFT8iU7FoBxzryNDMOpD1HIFHUSX4D87oqhQ== dependencies: "@types/json-buffer" "~3.0.0" json-buffer "~3.0.1" [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== concat-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-2.0.0.tgz#414cf5af790a48c60ab9be4527d56d5e41133cb1" integrity sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A== dependencies: buffer-from "^1.0.0" inherits "^2.0.3" readable-stream "^3.0.2" typedarray "^0.0.6" contains-path@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a" integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo= [email protected]: version "0.5.4" resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe" integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ== dependencies: safe-buffer "5.2.1" content-type@~1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b" integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA== [email protected]: version "1.0.6" resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c" integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw= [email protected]: version "0.5.0" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b" integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw== core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= cosmiconfig@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-6.0.0.tgz#da4fee853c52f6b1e6935f41c1a2fc50bd4a9982" integrity sha512-xb3ZL6+L8b9JLLCx3ZdoZy4+2ECphCMo2PwqgP1tlfVq6M6YReyzBJtvWWtbDSpNr9hn96pkCiZqUcFEc+54Qg== dependencies: "@types/parse-json" "^4.0.0" import-fresh "^3.1.0" parse-json "^5.0.0" path-type "^4.0.0" yaml "^1.7.2" cross-spawn@^6.0.5: version "6.0.5" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4" integrity sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ== dependencies: nice-try "^1.0.4" path-key "^2.0.1" semver "^5.5.0" shebang-command "^1.2.0" which "^1.2.9" cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== dependencies: path-key "^3.1.0" shebang-command "^2.0.0" which "^2.0.1" debug-log@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f" integrity sha1-IwdjLUwEOCuN+KMvcLiVBG1SdF8= [email protected], debug@^2.6.9: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" debug@^3.1.0: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" debug@^4.0.0: version "4.3.2" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== dependencies: ms "2.1.2" debug@^4.0.1, debug@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/debug/-/debug-4.1.1.tgz#3b72260255109c6b589cee050f1d516139664791" integrity sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw== dependencies: ms "^2.1.1" debug@^4.1.0, debug@^4.3.3, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" decode-named-character-reference@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz#daabac9690874c394c81e4162a0304b35d824f0e" integrity sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg== dependencies: character-entities "^2.0.0" decompress-response@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== dependencies: mimic-response "^3.1.0" dedent@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" integrity sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw= deep-eql@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df" integrity sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw== dependencies: type-detect "^4.0.0" deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== deep-is@^0.1.3, deep-is@~0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ= defaults@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.3.tgz#c656051e9817d9ff08ed881477f3fe4019f3ef7d" integrity sha1-xlYFHpgX2f8I7YgUd/P+QBnz730= dependencies: clone "^1.0.2" defer-to-connect@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587" integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg== define-properties@^1.1.2, define-properties@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== dependencies: object-keys "^1.0.12" deglob@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/deglob/-/deglob-4.0.1.tgz#0685c6383992fd6009be10653a2b1116696fad55" integrity sha512-/g+RDZ7yf2HvoW+E5Cy+K94YhgcFgr6C8LuHZD1O5HoNPkf3KY6RfXJ0DBGlB/NkLi5gml+G9zqRzk9S0mHZCg== dependencies: find-root "^1.0.0" glob "^7.0.5" ignore "^5.0.0" pkg-config "^1.1.0" run-parallel "^1.1.2" uniq "^1.0.1" delayed-stream@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== dequal@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== detect-node@^2.0.4: version "2.1.0" resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== diff@^3.1.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== diff@^5.0.0: version "5.1.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.1.0.tgz#bc52d298c5ea8df9194800224445ed43ffc87e40" integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" integrity sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA== dependencies: path-type "^4.0.0" [email protected]: version "1.5.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa" integrity sha1-N53Ocw9hZvds76TmcHoVmwLFpvo= dependencies: esutils "^2.0.2" isarray "^1.0.0" doctrine@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" integrity sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw== dependencies: esutils "^2.0.2" doctrine@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-3.0.0.tgz#addebead72a6574db783639dc87a121773973961" integrity sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w== dependencies: esutils "^2.0.2" dotenv-safe@^4.0.4: version "4.0.4" resolved "https://registry.yarnpkg.com/dotenv-safe/-/dotenv-safe-4.0.4.tgz#8b0e7ced8e70b1d3c5d874ef9420e406f39425b3" integrity sha1-iw587Y5wsdPF2HTvlCDkBvOUJbM= dependencies: dotenv "^4.0.0" dotenv@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-4.0.0.tgz#864ef1379aced55ce6f95debecdce179f7a0cd1d" integrity sha1-hk7xN5rO1Vzm+V3r7NzhefegzR0= dugite@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/dugite/-/dugite-2.3.0.tgz#ff6fdb4c899f84ed6695c9e01eaf4364a6211f13" integrity sha512-78zuD3p5lx2IS8DilVvHbXQXRo+hGIb3EAshTEC3ZyBLyArKegA8R/6c4Ne1aUlx6JRf3wmKNgYkdJOYMyj9aA== dependencies: progress "^2.0.3" tar "^6.1.11" duplexer@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= [email protected]: version "1.0.11" resolved "https://registry.yarnpkg.com/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz#ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf" integrity sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ== dependencies: safe-buffer "^5.0.1" [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.188: version "1.4.195" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.195.tgz#139b2d95a42a3f17df217589723a1deac71d1473" integrity sha512-vefjEh0sk871xNmR5whJf9TEngX+KTKS3hOHpjoMpauKkwlGwtMz1H8IaIjAT/GNnX0TbGwAdmVoXCAzXf+PPg== emoji-regex@^7.0.1: version "7.0.3" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-7.0.3.tgz#933a04052860c85e83c122479c4748a8e4c72156" integrity sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA== emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== emoji-regex@^9.2.2: version "9.2.2" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== emojis-list@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/emojis-list/-/emojis-list-3.0.0.tgz#5570662046ad29e2e916e71aae260abdff4f6a78" integrity sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q== encodeurl@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k= end-of-stream@^1.1.0: version "1.4.4" resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== dependencies: once "^1.4.0" enhanced-resolve@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz#41c7e0bfdfe74ac1ffe1e57ad6a5c6c9f3742a7f" integrity sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng== dependencies: graceful-fs "^4.1.2" memory-fs "^0.4.0" tapable "^1.0.0" enhanced-resolve@^5.9.3: version "5.10.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz#0dc579c3bb2a1032e357ac45b8f3a6f3ad4fb1e6" integrity sha512-T0yTFjdpldGY8PmuXXR0PyQ1ufZpEGiHVrp7zHKB7jdR4qlmZHhONVM5AQOAWXuF/w3dnHbEQVrNptJgt7F+cQ== dependencies: graceful-fs "^4.2.4" tapable "^2.2.0" enquirer@^2.3.5: version "2.3.6" resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== dependencies: ansi-colors "^4.1.1" ensure-posix-path@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/ensure-posix-path/-/ensure-posix-path-1.1.1.tgz#3c62bdb19fa4681544289edb2b382adc029179ce" integrity sha512-VWU0/zXzVbeJNXvME/5EmLuEj2TauvoaTz6aFYK1Z92JCBlDlZ3Gu0tuGR42kpW1754ywTs+QB0g5TP0oj9Zaw== entities@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/entities/-/entities-2.1.0.tgz#992d3129cf7df6870b96c57858c249a120f8b8b5" integrity sha512-hCx1oky9PFrJ611mf0ifBLBRW8lUUVRlFolb5gWRfIELabBlbp9xZvrqZLZAs+NxFnbfQoeGd8wDkygjg7U85w== entities@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== env-paths@^2.2.0, env-paths@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== envinfo@^7.7.3: version "7.8.1" resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== errno@^0.1.3: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" integrity sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg== dependencies: prr "~1.0.1" error-ex@^1.2.0, error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" es-abstract@^1.17.0, es-abstract@^1.17.0-next.1, es-abstract@^1.17.5: version "1.17.6" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== dependencies: es-to-primitive "^1.2.1" function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.1" is-callable "^1.2.0" is-regex "^1.1.0" object-inspect "^1.7.0" object-keys "^1.1.1" object.assign "^4.1.0" string.prototype.trimend "^1.0.1" string.prototype.trimstart "^1.0.1" es-abstract@^1.7.0: version "1.13.0" resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.13.0.tgz#ac86145fdd5099d8dd49558ccba2eaf9b88e24e9" integrity sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg== dependencies: es-to-primitive "^1.2.0" function-bind "^1.1.1" has "^1.0.3" is-callable "^1.1.4" is-regex "^1.0.4" object-keys "^1.0.12" es-module-lexer@^0.9.0: version "0.9.3" resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== es-to-primitive@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.0.tgz#edf72478033456e8dda8ef09e00ad9650707f377" integrity sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es-to-primitive@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== dependencies: is-callable "^1.1.4" is-date-object "^1.0.1" is-symbol "^1.0.2" es6-error@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/es6-error/-/es6-error-4.1.1.tgz#9e3af407459deed47e9a91f9b885a84eb05c561d" integrity sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg== es6-object-assign@^1.0.3: version "1.1.0" resolved "https://registry.yarnpkg.com/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" integrity sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg= escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= escape-string-regexp@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== [email protected]: version "8.1.0" resolved "https://registry.yarnpkg.com/eslint-config-standard-jsx/-/eslint-config-standard-jsx-8.1.0.tgz#314c62a0e6f51f75547f89aade059bec140edfc7" integrity sha512-ULVC8qH8qCqbU792ZOO6DaiaZyHNS/5CZt3hKqHkEhVlhPEPN3nfBqqxJCyp59XrjIBZPu1chMYe9T2DXZ7TMw== [email protected], eslint-config-standard@^14.1.1: version "14.1.1" resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-14.1.1.tgz#830a8e44e7aef7de67464979ad06b406026c56ea" integrity sha512-Z9B+VR+JIXRxz21udPTL9HpFMyoMUEeX1G251EQ6e05WD9aPVtVBn09XUmZ259wCMlCDmYDSZG62Hhm+ZTJcUg== eslint-import-resolver-node@^0.3.2, eslint-import-resolver-node@^0.3.3: version "0.3.4" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.4.tgz#85ffa81942c25012d8231096ddf679c03042c717" integrity sha512-ogtf+5AB/O+nM6DIeBUNr2fuT7ot9Qg/1harBfBtaP13ekEWFQEEMP94BCB7zaNW3gyY+8SHYF00rnqYwXKWOA== dependencies: debug "^2.6.9" resolve "^1.13.1" eslint-module-utils@^2.4.0, eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" integrity sha512-6j9xxegbqe8/kZY8cYpcp0xhbK0EgJlg3g9mib3/miLaExuuwc3n5UEfSnU6hWMbT0FAYVvDbL9RrRgpUeQIvA== dependencies: debug "^2.6.9" pkg-dir "^2.0.0" eslint-plugin-es@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-2.0.0.tgz#0f5f5da5f18aa21989feebe8a73eadefb3432976" integrity sha512-f6fceVtg27BR02EYnBhgWLFQfK6bN4Ll0nQFrBHOlCsAyxeZkn0NHns5O0YZOPrV1B3ramd6cgFwaoFLcSkwEQ== dependencies: eslint-utils "^1.4.2" regexpp "^3.0.0" eslint-plugin-es@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-es/-/eslint-plugin-es-3.0.1.tgz#75a7cdfdccddc0589934aeeb384175f221c57893" integrity sha512-GUmAsJaN4Fc7Gbtl8uOBlayo2DqhwWvEzykMHSCZHU3XdJ+NSzzZcVhXh3VxX5icqQ+oQdIEawXX8xkR3mIFmQ== dependencies: eslint-utils "^2.0.0" regexpp "^3.0.0" eslint-plugin-import@^2.22.0: version "2.22.0" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.22.0.tgz#92f7736fe1fde3e2de77623c838dd992ff5ffb7e" integrity sha512-66Fpf1Ln6aIS5Gr/55ts19eUuoDhAbZgnr6UxK5hbDx6l/QgQgx61AePq+BV4PP2uXQFClgMVzep5zZ94qqsxg== dependencies: array-includes "^3.1.1" array.prototype.flat "^1.2.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.3" eslint-module-utils "^2.6.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.1" read-pkg-up "^2.0.0" resolve "^1.17.0" tsconfig-paths "^3.9.0" eslint-plugin-import@~2.18.0: version "2.18.2" resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.18.2.tgz#02f1180b90b077b33d447a17a2326ceb400aceb6" integrity sha512-5ohpsHAiUBRNaBWAF08izwUGlbrJoJJ+W9/TBwsGoR1MnlgfwMIKrFeSjWbt6moabiXW9xNvtFz+97KHRfI4HQ== dependencies: array-includes "^3.0.3" contains-path "^0.1.0" debug "^2.6.9" doctrine "1.5.0" eslint-import-resolver-node "^0.3.2" eslint-module-utils "^2.4.0" has "^1.0.3" minimatch "^3.0.4" object.values "^1.1.0" read-pkg-up "^2.0.0" resolve "^1.11.0" eslint-plugin-mocha@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-mocha/-/eslint-plugin-mocha-7.0.1.tgz#b2e9e8ebef7836f999a83f8bab25d0e0c05f0d28" integrity sha512-zkQRW9UigRaayGm/pK9TD5RjccKXSgQksNtpsXbG9b6L5I+jNx7m98VUbZ4w1H1ArlNA+K7IOH+z8TscN6sOYg== dependencies: eslint-utils "^2.0.0" ramda "^0.27.0" eslint-plugin-node@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" integrity sha512-oUwtPJ1W0SKD0Tr+wqu92c5xuCeQqB3hSCHasn/ZgjFdA9iDGNkNf2Zi9ztY7X+hNuMib23LNGRm6+uN+KLE3g== dependencies: eslint-plugin-es "^3.0.0" eslint-utils "^2.0.0" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-node@~10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-10.0.0.tgz#fd1adbc7a300cf7eb6ac55cf4b0b6fc6e577f5a6" integrity sha512-1CSyM/QCjs6PXaT18+zuAXsjXGIGo5Rw630rSKwokSs2jrYURQc4R5JZpoanNCqwNmepg+0eZ9L7YiRUJb8jiQ== dependencies: eslint-plugin-es "^2.0.0" eslint-utils "^1.4.2" ignore "^5.1.1" minimatch "^3.0.4" resolve "^1.10.1" semver "^6.1.0" eslint-plugin-promise@~4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-4.2.1.tgz#845fd8b2260ad8f82564c1222fce44ad71d9418a" integrity sha512-VoM09vT7bfA7D+upt+FjeBO5eHIJQBUWki1aPvB+vbNiHS3+oGIJGIeyBtKQTME6UPXXy3vV07OL1tHd3ANuDw== eslint-plugin-react@~7.14.2: version "7.14.3" resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.14.3.tgz#911030dd7e98ba49e1b2208599571846a66bdf13" integrity sha512-EzdyyBWC4Uz2hPYBiEJrKCUi2Fn+BJ9B/pJQcjw5X+x/H2Nm59S4MJIvL4O5NEE0+WbnQwEBxWY03oUk+Bc3FA== dependencies: array-includes "^3.0.3" doctrine "^2.1.0" has "^1.0.3" jsx-ast-utils "^2.1.0" object.entries "^1.1.0" object.fromentries "^2.0.0" object.values "^1.1.0" prop-types "^15.7.2" resolve "^1.10.1" eslint-plugin-standard@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.1.tgz#ff0519f7ffaff114f76d1bd7c3996eef0f6e20b4" integrity sha512-v/KBnfyaOMPmZc/dmc6ozOdWqekGp7bBGq4jLAecEfPGmfKiWS4sA8sC0LqiV9w5qmXAtXVn4M3p1jSyhY85SQ== eslint-plugin-standard@~4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/eslint-plugin-standard/-/eslint-plugin-standard-4.0.0.tgz#f845b45109c99cd90e77796940a344546c8f6b5c" integrity sha512-OwxJkR6TQiYMmt1EsNRMe5qG3GsbjlcOhbGUBY4LtavF9DsLaTcoR+j2Tdjqi23oUwKNUqX7qcn5fPStafMdlA== eslint-plugin-typescript@^0.14.0: version "0.14.0" resolved "https://registry.yarnpkg.com/eslint-plugin-typescript/-/eslint-plugin-typescript-0.14.0.tgz#068549c3f4c7f3f85d88d398c29fa96bf500884c" integrity sha512-2u1WnnDF2mkWWgU1lFQ2RjypUlmRoBEvQN02y9u+IL12mjWlkKFGEBnVsjs9Y8190bfPQCvWly1c2rYYUSOxWw== dependencies: requireindex "~1.1.0" [email protected]: version "5.1.1" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== dependencies: esrecurse "^4.3.0" estraverse "^4.1.1" eslint-scope@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.0.0.tgz#e87c8887c73e8d1ec84f1ca591645c358bfc8fb9" integrity sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw== dependencies: esrecurse "^4.1.0" estraverse "^4.1.1" eslint-scope@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.0.tgz#d0f971dfe59c69e0cada684b23d49dbf82600ce5" integrity sha512-iiGRvtxWqgtx5m8EyQUJihBloE4EnYeGE/bz1wSPwJE6tZuJUtHlhqDM4Xj2ukE8Dyy1+HCZ4hE0fzIVMzb58w== dependencies: esrecurse "^4.1.0" estraverse "^4.1.1" eslint-utils@^1.4.2, eslint-utils@^1.4.3: version "1.4.3" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f" integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q== dependencies: eslint-visitor-keys "^1.1.0" eslint-utils@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" eslint-visitor-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2" integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A== eslint-visitor-keys@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== eslint-visitor-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.0.0.tgz#21fdc8fbcd9c795cc0321f0563702095751511a8" integrity sha512-QudtT6av5WXels9WjIM7qz1XD1cWGvX4gGXvp/zBn9nXG02D0utdU3Em2m/QjTnrsk6bBjmCygl3rmj118msQQ== eslint@^7.4.0: version "7.4.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.4.0.tgz#4e35a2697e6c1972f9d6ef2b690ad319f80f206f" integrity sha512-gU+lxhlPHu45H3JkEGgYhWhkR9wLHHEXC9FbWFnTlEkbKyZKWgWRLgf61E8zWmBuI6g5xKBph9ltg3NtZMVF8g== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^4.0.0" cross-spawn "^7.0.2" debug "^4.0.1" doctrine "^3.0.0" enquirer "^2.3.5" eslint-scope "^5.1.0" eslint-utils "^2.0.0" eslint-visitor-keys "^1.2.0" espree "^7.1.0" esquery "^1.2.0" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash "^4.17.14" minimatch "^3.0.4" natural-compare "^1.4.0" optionator "^0.9.1" progress "^2.0.0" regexpp "^3.1.0" semver "^7.2.1" strip-ansi "^6.0.0" strip-json-comments "^3.1.0" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" eslint@~6.8.0: version "6.8.0" resolved "https://registry.yarnpkg.com/eslint/-/eslint-6.8.0.tgz#62262d6729739f9275723824302fb227c8c93ffb" integrity sha512-K+Iayyo2LtyYhDSYwz5D5QdWw0hCacNzyq1Y821Xna2xSJj7cijoLLYmLxTQgcgZ9mC61nryMy9S7GRbYpI5Ig== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" chalk "^2.1.0" cross-spawn "^6.0.5" debug "^4.0.1" doctrine "^3.0.0" eslint-scope "^5.0.0" eslint-utils "^1.4.3" eslint-visitor-keys "^1.1.0" espree "^6.1.2" esquery "^1.0.1" esutils "^2.0.2" file-entry-cache "^5.0.1" functional-red-black-tree "^1.0.1" glob-parent "^5.0.0" globals "^12.1.0" ignore "^4.0.6" import-fresh "^3.0.0" imurmurhash "^0.1.4" inquirer "^7.0.0" is-glob "^4.0.0" js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.3.0" lodash "^4.17.14" minimatch "^3.0.4" mkdirp "^0.5.1" natural-compare "^1.4.0" optionator "^0.8.3" progress "^2.0.0" regexpp "^2.0.1" semver "^6.1.2" strip-ansi "^5.2.0" strip-json-comments "^3.0.1" table "^5.2.3" text-table "^0.2.0" v8-compile-cache "^2.0.3" espree@^6.1.2: version "6.2.1" resolved "https://registry.yarnpkg.com/espree/-/espree-6.2.1.tgz#77fc72e1fd744a2052c20f38a5b575832e82734a" integrity sha512-ysCxRQY3WaXJz9tdbWOwuWr5Y/XrPTGX9Kiz3yoUXwW0VZ4w30HTkQLaGx/+ttFjF8i+ACbArnB4ce68a9m5hw== dependencies: acorn "^7.1.1" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.1.0" espree@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/espree/-/espree-7.1.0.tgz#a9c7f18a752056735bf1ba14cb1b70adc3a5ce1c" integrity sha512-dcorZSyfmm4WTuTnE5Y7MEN1DyoPYy1ZR783QW1FJoenn7RailyWFsq/UL6ZAAA7uXurN9FIpYyUs3OfiIW+Qw== dependencies: acorn "^7.2.0" acorn-jsx "^5.2.0" eslint-visitor-keys "^1.2.0" esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== esquery@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" integrity sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA== dependencies: estraverse "^4.0.0" esquery@^1.2.0: version "1.3.1" resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.3.1.tgz#b78b5828aa8e214e29fb74c4d5b752e1c033da57" integrity sha512-olpvt9QG0vniUBZspVRN6lwB7hOZoTRtT+jzR+tS4ffYx2mzbw+z0XCOk44aaLYKApNX5nMm+E+P6o25ip/DHQ== dependencies: estraverse "^5.1.0" esrecurse@^4.1.0: version "4.2.1" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf" integrity sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ== dependencies: estraverse "^4.1.0" esrecurse@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== dependencies: estraverse "^5.2.0" estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1: version "4.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== estraverse@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.1.0.tgz#374309d39fd935ae500e7b92e8a6b4c720e59642" integrity sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw== estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== esutils@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== etag@~1.8.1: version "1.8.1" resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc= events-to-array@^1.0.1: version "1.1.2" resolved "https://registry.yarnpkg.com/events-to-array/-/events-to-array-1.1.2.tgz#2d41f563e1fe400ed4962fe1a4d5c6a7539df7f6" integrity sha1-LUH1Y+H+QA7Uli/hpNXGp1Od9/Y= [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/events/-/events-1.1.1.tgz#9ebdb7635ad099c70dcc4c2a1f5004288e8bd924" integrity sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ= events@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/events/-/events-3.0.0.tgz#9a0a0dfaf62893d92b875b8f2698ca4114973e88" integrity sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA== events@^3.2.0: version "3.3.0" resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== execa@^4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/execa/-/execa-4.0.3.tgz#0a34dabbad6d66100bd6f2c576c8669403f317f2" integrity sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A== dependencies: cross-spawn "^7.0.0" get-stream "^5.0.0" human-signals "^1.1.1" is-stream "^2.0.0" merge-stream "^2.0.0" npm-run-path "^4.0.0" onetime "^5.1.0" signal-exit "^3.0.2" strip-final-newline "^2.0.0" express@^4.16.4: version "4.18.2" resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59" integrity sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ== dependencies: accepts "~1.3.8" array-flatten "1.1.1" body-parser "1.20.1" content-disposition "0.5.4" content-type "~1.0.4" cookie "0.5.0" cookie-signature "1.0.6" debug "2.6.9" depd "2.0.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" finalhandler "1.2.0" fresh "0.5.2" http-errors "2.0.0" merge-descriptors "1.0.1" methods "~1.1.2" on-finished "2.4.1" parseurl "~1.3.3" path-to-regexp "0.1.7" proxy-addr "~2.0.7" qs "6.11.0" range-parser "~1.2.1" safe-buffer "5.2.1" send "0.18.0" serve-static "1.15.0" setprototypeof "1.2.0" statuses "2.0.1" type-is "~1.6.18" utils-merge "1.0.1" vary "~1.1.2" extend@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== external-editor@^3.0.3: version "3.1.0" resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== dependencies: chardet "^0.7.0" iconv-lite "^0.4.24" tmp "^0.0.33" extract-zip@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-2.0.1.tgz#663dca56fe46df890d5f131ef4a06d22bb8ba13a" integrity sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg== dependencies: debug "^4.1.1" get-stream "^5.1.0" yauzl "^2.10.0" optionalDependencies: "@types/yauzl" "^2.9.1" fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== fast-glob@^3.1.1: version "3.2.4" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.4.tgz#d20aefbf99579383e7f3cc66529158c9b98554d3" integrity sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ== dependencies: "@nodelib/fs.stat" "^2.0.2" "@nodelib/fs.walk" "^1.2.3" glob-parent "^5.1.0" merge2 "^1.3.0" micromatch "^4.0.2" picomatch "^2.2.1" fast-json-stable-stringify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= fastest-levenshtein@^1.0.12: version "1.0.14" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.14.tgz#9054384e4b7a78c88d01a4432dc18871af0ac859" integrity sha512-tFfWHjnuUfKE186Tfgr+jtaFc0mZTApEgKDOeyN+FwOqRkO/zK/3h1AiRd8u8CY53owL3CUmGr/oI9p/RdyLTA== fastq@^1.6.0: version "1.8.0" resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.8.0.tgz#550e1f9f59bbc65fe185cb6a9b4d95357107f481" integrity sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q== dependencies: reusify "^1.0.4" fault@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/fault/-/fault-2.0.0.tgz#ad2198a6e28e344dcda76a7b32406b1039f0b707" integrity sha512-JsDj9LFcoC+4ChII1QpXPA7YIaY8zmqPYw7h9j5n7St7a0BBKfNnwEBAUQRBx70o2q4rs+BeSNHk8Exm6xE7fQ== dependencies: format "^0.2.0" fd-slicer@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e" integrity sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g== dependencies: pend "~1.2.0" figgy-pudding@^3.5.1: version "3.5.2" resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e" integrity sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw== figures@^3.0.0, figures@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/figures/-/figures-3.2.0.tgz#625c18bd293c604dc4a8ddb2febf0c88341746af" integrity sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg== dependencies: escape-string-regexp "^1.0.5" file-entry-cache@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-5.0.1.tgz#ca0f6efa6dd3d561333fb14515065c2fafdf439c" integrity sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g== dependencies: flat-cache "^2.0.1" fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== dependencies: to-regex-range "^5.0.1" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32" integrity sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg== dependencies: debug "2.6.9" encodeurl "~1.0.2" escape-html "~1.0.3" on-finished "2.4.1" parseurl "~1.3.3" statuses "2.0.1" unpipe "~1.0.0" find-root@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng== find-up@^2.0.0, find-up@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= dependencies: locate-path "^2.0.0" find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" find-up@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== dependencies: locate-path "^5.0.0" path-exists "^4.0.0" flat-cache@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0" integrity sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA== dependencies: flatted "^2.0.0" rimraf "2.6.3" write "1.0.3" flatted@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08" integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg== folder-hash@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/folder-hash/-/folder-hash-2.1.2.tgz#7109f9cd0cbca271936d1b5544b156d6571e6cfd" integrity sha512-PmMwEZyNN96EMshf7sek4OIB7ADNsHOJ7VIw7pO0PBI0BNfEsi7U8U56TBjjqqwQ0WuBv8se0HEfmbw5b/Rk+w== dependencies: debug "^3.1.0" graceful-fs "~4.1.11" minimatch "~3.0.4" form-data@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" form-data@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" mime-types "^2.1.12" format@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/format/-/format-0.2.2.tgz#d6170107e9efdc4ed30c9dc39016df942b5cb58b" integrity sha1-1hcBB+nv3E7TDJ3DkBbflCtctYs= [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811" integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow== [email protected]: version "0.5.2" resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac= fs-extra@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.1.0.tgz#02873cfbc4084dde127eaa5f9905eef2325d1abf" integrity sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ== dependencies: graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^2.0.0" fs-extra@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-7.0.1.tgz#4f189c44aa123b895f722804f55ea23eadc348e9" integrity sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw== dependencies: graceful-fs "^4.1.2" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" integrity sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g== dependencies: graceful-fs "^4.2.0" jsonfile "^4.0.0" universalify "^0.1.0" fs-extra@^9.0.1: version "9.0.1" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.0.1.tgz#910da0062437ba4c39fedd863f1675ccfefcb9fc" integrity sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ== dependencies: at-least-node "^1.0.0" graceful-fs "^4.2.0" jsonfile "^6.0.1" universalify "^1.0.0" fs-minipass@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-2.1.0.tgz#7f5036fdbf12c63c169190cbe4199c852271f9fb" integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg== dependencies: minipass "^3.0.0" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== functional-red-black-tree@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= get-func-name@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41" integrity sha1-6td0q+5y4gQJQzoGY2YCPdaIekE= get-intrinsic@^1.0.2: version "1.2.0" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.0.tgz#7ad1dc0535f3a2904bba075772763e5051f6d05f" integrity sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q== dependencies: function-bind "^1.1.1" has "^1.0.3" has-symbols "^1.0.3" get-own-enumerable-property-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.0.tgz#b877b49a5c16aefac3655f2ed2ea5b684df8d203" integrity sha512-CIJYJC4GGF06TakLg8z4GQKvDsx9EMspVxOYih7LerEL/WosUnFIww45CGfxfeKHqlg3twgUrYRT1O3WQqjGCg== get-stdin@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-7.0.0.tgz#8d5de98f15171a125c5e516643c7a6d0ea8a96f6" integrity sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ== get-stdin@~9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-9.0.0.tgz#3983ff82e03d56f1b2ea0d3e60325f39d703a575" integrity sha512-dVKBjfWisLAicarI2Sf+JuBE/DghV4UzNAVe9yhEJuzeREd3JhOTE9cUaJTeSa77fsbQUK3pcOpJfM59+VKZaA== get-stream@^5.0.0, get-stream@^5.1.0: version "5.2.0" resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: pump "^3.0.0" getos@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/getos/-/getos-3.2.1.tgz#0134d1f4e00eb46144c5a9c0ac4dc087cbb27dc5" integrity sha512-U56CfOK17OKgTVqozZjUKNdkfEv6jk5WISBJ8SHoagjE6L69zOwl3Z+O8myjY9MEW3i2HPWQBt/LTbCgcC973Q== dependencies: async "^3.2.0" glob-parent@^5.0.0, glob-parent@^5.1.0, glob-parent@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" glob-to-regexp@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== glob@^7.0.0, glob@^7.0.5, glob@^7.1.3, glob@^7.1.6: version "7.2.0" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" glob@~8.0.3: version "8.0.3" resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" integrity sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^5.0.1" once "^1.3.0" global-agent@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/global-agent/-/global-agent-3.0.0.tgz#ae7cd31bd3583b93c5a16437a1afe27cc33a1ab6" integrity sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q== dependencies: boolean "^3.0.1" es6-error "^4.1.1" matcher "^3.0.0" roarr "^2.15.3" semver "^7.3.2" serialize-error "^7.0.1" globals@^12.1.0: version "12.4.0" resolved "https://registry.yarnpkg.com/globals/-/globals-12.4.0.tgz#a18813576a41b00a24a97e7f815918c2e19925f8" integrity sha512-BWICuzzDvDoH54NHKCseDanAhE3CeDorgDL5MT6LMXXj2WCnd9UC2szdk4AWLfjdgNBCXLUanXYcpBBKOSWGwg== dependencies: type-fest "^0.8.1" globalthis@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/globalthis/-/globalthis-1.0.3.tgz#5852882a52b80dc301b0660273e1ed082f0b6ccf" integrity sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA== dependencies: define-properties "^1.1.3" globby@^11.0.0, globby@^11.0.1: version "11.0.1" resolved "https://registry.yarnpkg.com/globby/-/globby-11.0.1.tgz#9a2bf107a068f3ffeabc49ad702c79ede8cfd357" integrity sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ== dependencies: array-union "^2.1.0" dir-glob "^3.0.1" fast-glob "^3.1.1" ignore "^5.1.4" merge2 "^1.3.0" slash "^3.0.0" got@^11.8.5: version "11.8.5" resolved "https://registry.yarnpkg.com/got/-/got-11.8.5.tgz#ce77d045136de56e8f024bebb82ea349bc730046" integrity sha512-o0Je4NvQObAuZPHLFoRSkdG2lTgtcynqymzg2Vupdx6PorhaT5MCbIyXG6d4D94kk8ZG57QeosgdiqfJWhEhlQ== dependencies: "@sindresorhus/is" "^4.0.0" "@szmarczak/http-timer" "^4.0.5" "@types/cacheable-request" "^6.0.1" "@types/responselike" "^1.0.0" cacheable-lookup "^5.0.3" cacheable-request "^7.0.2" decompress-response "^6.0.0" http2-wrapper "^1.0.0-beta.5.2" lowercase-keys "^2.0.0" p-cancelable "^2.0.0" responselike "^2.0.0" graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.9: version "4.2.0" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.0.tgz#8d8fdc73977cb04104721cb53666c1ca64cd328b" integrity sha512-jpSvDPV4Cq/bgtpndIWbI5hmYxhQGHPC4d4cqBPb4DLniCfhJokdXhwhaDuLBGLQdvvRum/UiX6ECVIPvDXqdg== graceful-fs@^4.1.6, graceful-fs@^4.2.0: version "4.2.3" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.3.tgz#4a12ff1b60376ef09862c2093edd908328be8423" integrity sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ== graceful-fs@^4.2.4, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== graceful-fs@~4.1.11: version "4.1.15" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00" integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA== has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== has-flag@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-5.0.1.tgz#5483db2ae02a472d1d0691462fc587d1843cd940" integrity sha512-CsNUt5x9LUdx6hnk/E2SZLsDyvfqANZSUq4+D3D8RzDJ2M+HDTIkF60ibS1vHaK55vzgiZw1bEPFG9yH7l33wA== has-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.0.tgz#ba1a8f1af2a0fc39650f5c850367704122063b44" integrity sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q= has-symbols@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== has-symbols@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== has@^1.0.1, has@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== dependencies: function-bind "^1.1.1" hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw== http-cache-semantics@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3" integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ== dependencies: depd "2.0.0" inherits "2.0.4" setprototypeof "1.2.0" statuses "2.0.1" toidentifier "1.0.1" http2-wrapper@^1.0.0-beta.5.2: version "1.0.3" resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-1.0.3.tgz#b8f55e0c1f25d4ebd08b3b0c2c079f9590800b3d" integrity sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg== dependencies: quick-lru "^5.1.1" resolve-alpn "^1.0.0" human-signals@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw== husky@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.1.tgz#511cb3e57de3e3190514ae49ed50f6bc3f50b3e9" integrity sha512-xs7/chUH/CKdOCs7Zy0Aev9e/dKOMZf3K1Az1nar3tzlv0jfqnYtu235bstsWTmXOR0EfINrPa97yy4Lz6RiKw== [email protected], iconv-lite@^0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" [email protected], ieee754@^1.1.4: version "1.1.13" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.13.tgz#ec168558e95aa181fd87d37f55c32bbcb6708b84" integrity sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg== ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== ignore@^4.0.6: version "4.0.6" resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== ignore@^5.0.0, ignore@^5.1.1, ignore@^5.1.4: version "5.1.8" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57" integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw== ignore@~5.2.4: version "5.2.4" resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== import-fresh@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.1.0.tgz#6d33fa1dcef6df930fae003446f33415af905118" integrity sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-fresh@^3.1.0: version "3.2.1" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66" integrity sha512-6e1q1cnWP2RXD9/keSkxHScg508CdXqXWgWBaETNhyuBFz+kUZlKboh+ISK+bU++DmbHimVBrOz/zzPe0sZ3sQ== dependencies: parent-module "^1.0.0" resolve-from "^4.0.0" import-local@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.1.0.tgz#b4479df8a5fd44f6cdce24070675676063c95cb4" integrity sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg== dependencies: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" import-meta-resolve@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-1.1.1.tgz#244fd542fd1fae73550d4f8b3cde3bba1d7b2b18" integrity sha512-JiTuIvVyPaUg11eTrNDx5bgQ/yMKMZffc7YSjvQeSMXy58DO2SQ8BtAf3xteZvmzvjYh14wnqNjL8XVeDy2o9A== dependencies: builtins "^4.0.0" imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= indent-string@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2, [email protected], inherits@^2.0.3, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@^1.3.5: version "1.3.7" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.7.tgz#a09363e1911972ea16d7a8851005d84cf09a9a84" integrity sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ== ini@~3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/ini/-/ini-3.0.1.tgz#c76ec81007875bc44d544ff7a11a55d12294102d" integrity sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ== inquirer@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.3.0.tgz#aa3e7cb0c18a410c3c16cdd2bc9dcbe83c4d333e" integrity sha512-K+LZp6L/6eE5swqIcVXrxl21aGDU4S50gKH0/d96OMQnSBCyGyZl/oZhbkVmdp5sBoINHd4xZvFSARh2dk6DWA== dependencies: ansi-escapes "^4.2.1" chalk "^4.1.0" cli-cursor "^3.1.0" cli-width "^3.0.0" external-editor "^3.0.3" figures "^3.0.0" lodash "^4.17.15" mute-stream "0.0.8" run-async "^2.4.0" rxjs "^6.6.0" string-width "^4.1.0" strip-ansi "^6.0.0" through "^2.3.6" interpret@^1.0.0: version "1.4.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== interpret@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== [email protected]: version "1.9.1" resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3" integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g== is-alphabetical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-2.0.0.tgz#ef6e2caea57c63450fffc7abb6cbdafc5eb96e96" integrity sha512-5OV8Toyq3oh4eq6sbWTYzlGdnMT/DPI5I0zxUBxjiigQsZycpkKF3kskkao3JyYGuYDHvhgJF+DrjMQp9SX86w== is-alphanumerical@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-alphanumerical/-/is-alphanumerical-2.0.0.tgz#0fbfeb6a72d21d91143b3d182bf6cf5909ee66f6" integrity sha512-t+2GlJ+hO9yagJ+jU3+HSh80VKvz/3cG2cxbGGm4S0hjKuhWQXgPVUVOZz3tqZzMjhmphZ+1TIJTlRZRoe6GCQ== dependencies: is-alphabetical "^2.0.0" is-decimal "^2.0.0" is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09" integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw== dependencies: binary-extensions "^2.0.0" is-buffer@^2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.5.tgz#ebc252e400d22ff8d77fa09888821a24a658c191" integrity sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ== is-callable@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.4.tgz#1e1adf219e1eeb684d691f9d6a05ff0d30a24d75" integrity sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA== is-callable@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.0.tgz#83336560b54a38e35e3a2df7afd0454d691468bb" integrity sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw== is-core-module@^2.8.0: version "2.8.1" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.8.1.tgz#f59fdfca701d5879d0a6b100a40aa1560ce27211" integrity sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA== dependencies: has "^1.0.3" is-core-module@^2.9.0: version "2.9.0" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== dependencies: has "^1.0.3" is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= is-decimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-2.0.0.tgz#db1140337809fd043a056ae40a9bd1cdc563034c" integrity sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw== is-empty@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/is-empty/-/is-empty-1.2.0.tgz#de9bb5b278738a05a0b09a57e1fb4d4a341a9f6b" integrity sha1-3pu1snhzigWgsJpX4ftNSjQan2s= is-extglob@^2.1.0, is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-fullwidth-code-point@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== is-fullwidth-code-point@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== is-glob@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= dependencies: is-extglob "^2.1.0" is-glob@^4.0.0, is-glob@^4.0.1, is-glob@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== dependencies: is-extglob "^2.1.1" is-hexadecimal@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-hexadecimal/-/is-hexadecimal-2.0.0.tgz#8e1ec9f48fe3eabd90161109856a23e0907a65d5" integrity sha512-vGOtYkiaxwIiR0+Ng/zNId+ZZehGfINwTzdrDqc6iubbnQWhnPuYymOzOKUDqa2cSl59yHnEh2h6MvRLQsyNug== is-interactive@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== is-obj@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= is-plain-obj@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-4.0.0.tgz#06c0999fd7574edf5a906ba5644ad0feb3a84d22" integrity sha512-NXRbBtUdBioI73y/HmOhogw/U5msYPC9DAtGkJXeFcFWSFZw0mCUsPxk/snTuJHzNKA8kLBK4rH97RMB1BfCXw== is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-plain-object@^4.0.0: version "4.1.1" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-4.1.1.tgz#1a14d6452cbd50790edc7fdaa0aed5a40a35ebb5" integrity sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA== is-plain-object@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== is-regex@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.0.4.tgz#5517489b547091b0930e095654ced25ee97e9491" integrity sha1-VRdIm1RwkbCTDglWVM7SXul+lJE= dependencies: has "^1.0.1" is-regex@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.0.tgz#ece38e389e490df0dc21caea2bd596f987f767ff" integrity sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw== dependencies: has-symbols "^1.0.1" is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= is-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== is-string@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== is-symbol@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.2.tgz#a055f6ae57192caee329e7a860118b497a950f38" integrity sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw== dependencies: has-symbols "^1.0.0" isarray@^1.0.0, isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= jest-worker@^27.4.5: version "27.5.1" resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== dependencies: "@types/node" "*" merge-stream "^2.0.0" supports-color "^8.0.0" [email protected]: version "0.15.0" resolved "https://registry.yarnpkg.com/jmespath/-/jmespath-0.15.0.tgz#a3f222a9aae9f966f5d27c796510e28091764217" integrity sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc= "js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== js-yaml@^3.13.1, js-yaml@^3.2.7: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" integrity sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw== dependencies: argparse "^1.0.7" esprima "^4.0.0" js-yaml@^4.0.0, js-yaml@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== dependencies: argparse "^2.0.1" [email protected], json-buffer@~3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== json-parse-even-better-errors@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= json-stringify-safe@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== json5@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA== dependencies: minimist "^1.2.0" json5@^2.0.0, json5@^2.1.2: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== jsonc-parser@~3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== jsonfile@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-4.0.0.tgz#8771aae0799b64076b76640fca058f9c10e33ecb" integrity sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss= optionalDependencies: graceful-fs "^4.1.6" jsonfile@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.0.1.tgz#98966cba214378c8c84b82e085907b40bf614179" integrity sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg== dependencies: universalify "^1.0.0" optionalDependencies: graceful-fs "^4.1.6" jsonwebtoken@^9.0.0: version "9.0.0" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz#d0faf9ba1cc3a56255fe49c0961a67e520c1926d" integrity sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw== dependencies: jws "^3.2.2" lodash "^4.17.21" ms "^2.1.1" semver "^7.3.8" jsx-ast-utils@^2.1.0: version "2.4.1" resolved "https://registry.yarnpkg.com/jsx-ast-utils/-/jsx-ast-utils-2.4.1.tgz#1114a4c1209481db06c690c2b4f488cc665f657e" integrity sha512-z1xSldJ6imESSzOjd3NNkieVJKRlKYSOtMG8SFyCj2FIrvSaSuli/WjpBkEzCBoR9bYYYFgqJw61Xhu7Lcgk+w== dependencies: array-includes "^3.1.1" object.assign "^4.1.0" jwa@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/jwa/-/jwa-1.4.1.tgz#743c32985cb9e98655530d53641b66c8645b039a" integrity sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA== dependencies: buffer-equal-constant-time "1.0.1" ecdsa-sig-formatter "1.0.11" safe-buffer "^5.0.1" jws@^3.2.2: version "3.2.2" resolved "https://registry.yarnpkg.com/jws/-/jws-3.2.2.tgz#001099f3639468c9414000e99995fa52fb478304" integrity sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA== dependencies: jwa "^1.4.1" safe-buffer "^5.0.1" keyv@^4.0.0: version "4.3.1" resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.3.1.tgz#7970672f137d987945821b1a07b524ce5a4edd27" integrity sha512-nwP7AQOxFzELXsNq3zCx/oh81zu4DHWwCE6W9RaeHb7OHO0JpmKS8n801ovVQC7PTsZDWtPA5j1QY+/WWtARYg== dependencies: compress-brotli "^1.3.8" json-buffer "3.0.1" kind-of@^6.0.2: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== klaw@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" integrity sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g== dependencies: graceful-fs "^4.1.9" kleur@^4.0.3: version "4.1.5" resolved "https://registry.yarnpkg.com/kleur/-/kleur-4.1.5.tgz#95106101795f7050c6c650f350c683febddb1780" integrity sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ== levn@^0.3.0, levn@~0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" integrity sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4= dependencies: prelude-ls "~1.1.2" type-check "~0.3.2" levn@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== dependencies: prelude-ls "^1.2.1" type-check "~0.4.0" libnpmconfig@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/libnpmconfig/-/libnpmconfig-1.2.1.tgz#c0c2f793a74e67d4825e5039e7a02a0044dfcbc0" integrity sha512-9esX8rTQAHqarx6qeZqmGQKBNZR5OIbl/Ayr0qQDy3oXja2iFVQQI81R6GZ2a02bSNZ9p3YOGX1O6HHCb1X7kA== dependencies: figgy-pudding "^3.5.1" find-up "^3.0.0" ini "^1.3.5" lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= linkify-it@^3.0.1: version "3.0.3" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-3.0.3.tgz#a98baf44ce45a550efb4d49c769d07524cc2fa2e" integrity sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ== dependencies: uc.micro "^1.0.1" linkify-it@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-4.0.1.tgz#01f1d5e508190d06669982ba31a7d9f56a5751ec" integrity sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw== dependencies: uc.micro "^1.0.1" lint-staged@^10.2.11: version "10.2.11" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-10.2.11.tgz#713c80877f2dc8b609b05bc59020234e766c9720" integrity sha512-LRRrSogzbixYaZItE2APaS4l2eJMjjf5MbclRZpLJtcQJShcvUzKXsNeZgsLIZ0H0+fg2tL4B59fU9wHIHtFIA== dependencies: chalk "^4.0.0" cli-truncate "2.1.0" commander "^5.1.0" cosmiconfig "^6.0.0" debug "^4.1.1" dedent "^0.7.0" enquirer "^2.3.5" execa "^4.0.1" listr2 "^2.1.0" log-symbols "^4.0.0" micromatch "^4.0.2" normalize-path "^3.0.0" please-upgrade-node "^3.2.0" string-argv "0.3.1" stringify-object "^3.3.0" lint@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/lint/-/lint-1.1.2.tgz#35ed064f322547c331358d899868664968ba371f" integrity sha1-Ne0GTzIlR8MxNY2JmGhmSWi6Nx8= listr2@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/listr2/-/listr2-2.2.0.tgz#cb88631258abc578c7fb64e590fe5742f28e4aac" integrity sha512-Q8qbd7rgmEwDo1nSyHaWQeztfGsdL6rb4uh7BA+Q80AZiDET5rVntiU1+13mu2ZTDVaBVbvAD1Db11rnu3l9sg== dependencies: chalk "^4.0.0" cli-truncate "^2.1.0" figures "^3.2.0" indent-string "^4.0.0" log-update "^4.0.0" p-map "^4.0.0" rxjs "^6.5.5" through "^2.3.8" load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-2.0.0.tgz#7947e42149af80d696cbf797bcaabcfe1fe29ca8" integrity sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg= dependencies: graceful-fs "^4.1.2" parse-json "^2.2.0" pify "^2.0.0" strip-bom "^3.0.0" load-json-file@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-5.3.0.tgz#4d3c1e01fa1c03ea78a60ac7af932c9ce53403f3" integrity sha512-cJGP40Jc/VXUsp8/OrnyKyTZ1y6v/dphm3bioS+RrKXjK2BB6wHUd6JptZEFDGgGahMT+InnZO5i1Ei9mpC8Bw== dependencies: graceful-fs "^4.1.15" parse-json "^4.0.0" pify "^4.0.1" strip-bom "^3.0.0" type-fest "^0.3.0" load-plugin@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/load-plugin/-/load-plugin-4.0.1.tgz#9a239b0337064c9b8aac82b0c9f89b067db487c5" integrity sha512-4kMi+mOSn/TR51pDo4tgxROHfBHXsrcyEYSGHcJ1o6TtRaP2PsRM5EwmYbj1uiLDvbfA/ohwuSWZJzqGiai8Dw== dependencies: import-meta-resolve "^1.0.0" libnpmconfig "^1.0.0" loader-runner@^4.2.0: version "4.3.0" resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== loader-utils@^1.0.2: version "1.4.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" integrity sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^1.0.1" loader-utils@^2.0.0: version "2.0.4" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c" integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw== dependencies: big.js "^5.2.2" emojis-list "^3.0.0" json5 "^2.1.2" locate-path@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" integrity sha1-K1aLJl7slExtnA3pw9u7ygNUzY4= dependencies: p-locate "^2.0.0" path-exists "^3.0.0" locate-path@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-3.0.0.tgz#dbec3b3ab759758071b58fe59fc41871af21400e" integrity sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A== dependencies: p-locate "^3.0.0" path-exists "^3.0.0" locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== dependencies: p-locate "^4.1.0" lodash.camelcase@^4.3.0: version "4.3.0" resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" integrity sha1-soqmKIorn8ZRA1x3EfZathkDMaY= lodash.flatten@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f" integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8= lodash.range@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/lodash.range/-/lodash.range-3.2.0.tgz#f461e588f66683f7eadeade513e38a69a565a15d" integrity sha1-9GHliPZmg/fq3q3lE+OKaaVloV0= lodash@^4.0.0, lodash@^4.17.11, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.2.0.tgz#5740e1c5d6f0dfda4ad9323b5332107ef6b4c40a" integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg== dependencies: chalk "^2.0.1" log-symbols@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" integrity sha512-dSkNGuI7iG3mfvDzUuYZyvk5dD9ocYCYzNU6CYDE6+Xqd+gwme6Z00NS3dUh8mq/73HaEtT7m6W+yUPtU6BZnQ== dependencies: chalk "^2.4.2" log-symbols@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== dependencies: chalk "^4.0.0" log-update@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== dependencies: ansi-escapes "^4.3.0" cli-cursor "^3.1.0" slice-ansi "^4.0.0" wrap-ansi "^6.2.0" longest-streak@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/longest-streak/-/longest-streak-3.0.0.tgz#f127e2bded83caa6a35ac5f7a2f2b2f94b36f3dc" integrity sha512-XhUjWR5CFaQ03JOP+iSDS9koy8T5jfoImCZ4XprElw3BXsSk4MpVYOLw/6LTDKZhO13PlAXnB5gS4MHQTpkSOw== loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== dependencies: js-tokens "^3.0.0 || ^4.0.0" lowercase-keys@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" make-error@^1.1.1: version "1.3.5" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== [email protected]: version "13.0.1" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-13.0.1.tgz#c6ecc431cacf1a5da531423fc6a42807814af430" integrity sha512-lTlxriVoy2criHP0JKRhO2VDG9c2ypWCsT237eDiLqi09rmbKoUetyGHq2uOIRoRS//kfoJckS0eUzzkDR+k2Q== dependencies: argparse "^2.0.1" entities "~3.0.1" linkify-it "^4.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdown-it@^12.0.0: version "12.3.2" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-12.3.2.tgz#bf92ac92283fe983fe4de8ff8abfb5ad72cd0c90" integrity sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg== dependencies: argparse "^2.0.1" entities "~2.1.0" linkify-it "^3.0.1" mdurl "^1.0.1" uc.micro "^1.0.5" markdownlint-cli@^0.33.0: version "0.33.0" resolved "https://registry.yarnpkg.com/markdownlint-cli/-/markdownlint-cli-0.33.0.tgz#703af1234c32c309ab52fcd0e8bc797a34e2b096" integrity sha512-zMK1oHpjYkhjO+94+ngARiBBrRDEUMzooDHBAHtmEIJ9oYddd9l3chCReY2mPlecwH7gflQp1ApilTo+o0zopQ== dependencies: commander "~9.4.1" get-stdin "~9.0.0" glob "~8.0.3" ignore "~5.2.4" js-yaml "^4.1.0" jsonc-parser "~3.2.0" markdownlint "~0.27.0" minimatch "~5.1.2" run-con "~1.2.11" markdownlint@~0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.27.0.tgz#9dabf7710a4999e2835e3c68317f1acd0bc89049" integrity sha512-HtfVr/hzJJmE0C198F99JLaeada+646B5SaG2pVoEakLFI6iRGsvMqrnnrflq8hm1zQgwskEgqSnhDW11JBp0w== dependencies: markdown-it "13.0.1" matcher-collection@^1.0.0: version "1.1.2" resolved "https://registry.yarnpkg.com/matcher-collection/-/matcher-collection-1.1.2.tgz#1076f506f10ca85897b53d14ef54f90a5c426838" integrity sha512-YQ/teqaOIIfUHedRam08PB3NK7Mjct6BvzRnJmpGDm8uFXpNr1sbY4yuflI5JcEs6COpYA0FpRQhSDBf1tT95g== dependencies: minimatch "^3.0.2" matcher@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca" integrity sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng== dependencies: escape-string-regexp "^4.0.0" mdast-comment-marker@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-comment-marker/-/mdast-comment-marker-1.1.1.tgz#9c9c18e1ed57feafc1965d92b028f37c3c8da70d" integrity sha512-TWZDaUtPLwKX1pzDIY48MkSUQRDwX/HqbTB4m3iYdL/zosi/Z6Xqfdv0C0hNVKvzrPjZENrpWDt4p4odeVO0Iw== mdast-util-from-markdown@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.0.0.tgz#c517313cd999ec2b8f6d447b438c5a9d500b89c9" integrity sha512-uj2G60sb7z1PNOeElFwCC9b/Se/lFXuLhVKFOAY2EHz/VvgbupTQRNXPoZl7rGpXYL6BNZgcgaybrlSWbo7n/g== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" mdast-util-to-string "^3.0.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" unist-util-stringify-position "^3.0.0" mdast-util-from-markdown@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.2.0.tgz#84df2924ccc6c995dec1e2368b2b208ad0a76268" integrity sha512-iZJyyvKD1+K7QX1b5jXdE7Sc5dtoTry1vzV28UZZe8Z1xVnB/czKntJ7ZAkG0tANqRnBF6p3p7GpU1y19DTf2Q== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" decode-named-character-reference "^1.0.0" mdast-util-to-string "^3.1.0" micromark "^3.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-decode-string "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" unist-util-stringify-position "^3.0.0" uvu "^0.5.0" mdast-util-heading-style@^1.0.2: version "1.0.5" resolved "https://registry.yarnpkg.com/mdast-util-heading-style/-/mdast-util-heading-style-1.0.5.tgz#81b2e60d76754198687db0e8f044e42376db0426" integrity sha512-8zQkb3IUwiwOdUw6jIhnwM6DPyib+mgzQuHAe7j2Hy1rIarU4VUxe472bp9oktqULW3xqZE+Kz6OD4Gi7IA3vw== mdast-util-to-markdown@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/mdast-util-to-markdown/-/mdast-util-to-markdown-1.1.1.tgz#545ccc4dcc6672614b84fd1064482320dd689b12" integrity sha512-4puev/CxuxVdlsx5lVmuzgdqfjkkJJLS1Zm/MnejQ8I7BLeeBlbkwp6WOGJypEcN8g56LbVbhNmn84MvvcAvSQ== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" longest-streak "^3.0.0" mdast-util-to-string "^3.0.0" parse-entities "^3.0.0" zwitch "^2.0.0" mdast-util-to-string@^1.0.2: version "1.0.6" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-1.0.6.tgz#7d85421021343b33de1552fc71cb8e5b4ae7536d" integrity sha512-868pp48gUPmZIhfKrLbaDneuzGiw3OTDjHc5M1kAepR2CWBJ+HpEsm252K4aXdiP5coVZaJPOqGtVU6Po8xnXg== mdast-util-to-string@^3.0.0, mdast-util-to-string@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mdast-util-to-string/-/mdast-util-to-string-3.1.0.tgz#56c506d065fbf769515235e577b5a261552d56e9" integrity sha512-n4Vypz/DZgwo0iMHLQL49dJzlp7YtAJP+N07MZHpjPf/5XJuHUWstviF4Mn2jEiR/GNmtnRRqnwsXExk3igfFA== mdurl@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= [email protected]: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" integrity sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g= memory-fs@^0.4.0: version "0.4.1" resolved "https://registry.yarnpkg.com/memory-fs/-/memory-fs-0.4.1.tgz#3a9a20b8462523e447cfbc7e8bb80ed667bfc552" integrity sha1-OpoguEYlI+RHz7x+i7gO1me/xVI= dependencies: errno "^0.1.3" readable-stream "^2.0.1" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61" integrity sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E= merge-stream@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== merge2@^1.3.0: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== methods@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= micromark-core-commonmark@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-core-commonmark/-/micromark-core-commonmark-1.0.0.tgz#b767fa7687c205c224175bf067796360a3830350" integrity sha512-y9g7zymcKRBHM/aNBekstvs/Grpf+y4OEBULUTYvGZcusnp+JeOxmilJY4GMpo2/xY7iHQL9fjz5pD9pSAud9A== dependencies: micromark-factory-destination "^1.0.0" micromark-factory-label "^1.0.0" micromark-factory-space "^1.0.0" micromark-factory-title "^1.0.0" micromark-factory-whitespace "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-classify-character "^1.0.0" micromark-util-html-tag-name "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromark-factory-destination@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-destination/-/micromark-factory-destination-1.0.0.tgz#fef1cb59ad4997c496f887b6977aa3034a5a277e" integrity sha512-eUBA7Rs1/xtTVun9TmV3gjfPz2wEwgK5R5xcbIM5ZYAtvGF6JkyaDsj0agx8urXnO31tEO6Ug83iVH3tdedLnw== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-label@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-label/-/micromark-factory-label-1.0.0.tgz#b316ec479b474232973ff13b49b576f84a6f2cbb" integrity sha512-XWEucVZb+qBCe2jmlOnWr6sWSY6NHx+wtpgYFsm4G+dufOf6tTQRRo0bdO7XSlGPu5fyjpJenth6Ksnc5Mwfww== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-space@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-space/-/micromark-factory-space-1.0.0.tgz#cebff49968f2b9616c0fcb239e96685cb9497633" integrity sha512-qUmqs4kj9a5yBnk3JMLyjtWYN6Mzfcx8uJfi5XAveBniDevmZasdGBba5b4QsvRcAkmvGo5ACmSUmyGiKTLZew== dependencies: micromark-util-character "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-title@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-title/-/micromark-factory-title-1.0.0.tgz#708f7a8044f34a898c0efdb4f55e4da66b537273" integrity sha512-flvC7Gx0dWVWorXuBl09Cr3wB5FTuYec8pMGVySIp2ZlqTcIjN/lFohZcP0EG//krTptm34kozHk7aK/CleCfA== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-factory-whitespace@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-factory-whitespace/-/micromark-factory-whitespace-1.0.0.tgz#e991e043ad376c1ba52f4e49858ce0794678621c" integrity sha512-Qx7uEyahU1lt1RnsECBiuEbfr9INjQTGa6Err+gF3g0Tx4YEviPbqqGKNv/NrBaE7dVHdn1bVZKM/n5I/Bak7A== dependencies: micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-character@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/micromark-util-character/-/micromark-util-character-1.1.0.tgz#d97c54d5742a0d9611a68ca0cd4124331f264d86" integrity sha512-agJ5B3unGNJ9rJvADMJ5ZiYjBRyDpzKAOk01Kpi1TKhlT1APx3XZk6eN7RtSz1erbWHC2L8T3xLZ81wdtGRZzg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-chunked@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-chunked/-/micromark-util-chunked-1.0.0.tgz#5b40d83f3d53b84c4c6bce30ed4257e9a4c79d06" integrity sha512-5e8xTis5tEZKgesfbQMKRCyzvffRRUX+lK/y+DvsMFdabAicPkkZV6gO+FEWi9RfuKKoxxPwNL+dFF0SMImc1g== dependencies: micromark-util-symbol "^1.0.0" micromark-util-classify-character@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-classify-character/-/micromark-util-classify-character-1.0.0.tgz#cbd7b447cb79ee6997dd274a46fc4eb806460a20" integrity sha512-F8oW2KKrQRb3vS5ud5HIqBVkCqQi224Nm55o5wYLzY/9PwHGXC01tr3d7+TqHHz6zrKQ72Okwtvm/xQm6OVNZA== dependencies: micromark-util-character "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-combine-extensions@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.0.0.tgz#91418e1e74fb893e3628b8d496085639124ff3d5" integrity sha512-J8H058vFBdo/6+AsjHp2NF7AJ02SZtWaVUjsayNFeAiydTxUwViQPxN0Hf8dp4FmCQi0UUFovFsEyRSUmFH3MA== dependencies: micromark-util-chunked "^1.0.0" micromark-util-types "^1.0.0" micromark-util-decode-numeric-character-reference@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.0.0.tgz#dcc85f13b5bd93ff8d2868c3dba28039d490b946" integrity sha512-OzO9AI5VUtrTD7KSdagf4MWgHMtET17Ua1fIpXTpuhclCqD8egFWo85GxSGvxgkGS74bEahvtM0WP0HjvV0e4w== dependencies: micromark-util-symbol "^1.0.0" micromark-util-decode-string@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/micromark-util-decode-string/-/micromark-util-decode-string-1.0.2.tgz#942252ab7a76dec2dbf089cc32505ee2bc3acf02" integrity sha512-DLT5Ho02qr6QWVNYbRZ3RYOSSWWFuH3tJexd3dgN1odEuPNxCngTCXJum7+ViRAd9BbdxCvMToPOD/IvVhzG6Q== dependencies: decode-named-character-reference "^1.0.0" micromark-util-character "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-encode@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-encode/-/micromark-util-encode-1.0.0.tgz#c409ecf751a28aa9564b599db35640fccec4c068" integrity sha512-cJpFVM768h6zkd8qJ1LNRrITfY4gwFt+tziPcIf71Ui8yFzY9wG3snZQqiWVq93PG4Sw6YOtcNiKJfVIs9qfGg== micromark-util-html-tag-name@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.0.0.tgz#75737e92fef50af0c6212bd309bc5cb8dbd489ed" integrity sha512-NenEKIshW2ZI/ERv9HtFNsrn3llSPZtY337LID/24WeLqMzeZhBEE6BQ0vS2ZBjshm5n40chKtJ3qjAbVV8S0g== micromark-util-normalize-identifier@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.0.0.tgz#4a3539cb8db954bbec5203952bfe8cedadae7828" integrity sha512-yg+zrL14bBTFrQ7n35CmByWUTFsgst5JhA4gJYoty4Dqzj4Z4Fr/DHekSS5aLfH9bdlfnSvKAWsAgJhIbogyBg== dependencies: micromark-util-symbol "^1.0.0" micromark-util-resolve-all@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-resolve-all/-/micromark-util-resolve-all-1.0.0.tgz#a7c363f49a0162e931960c44f3127ab58f031d88" integrity sha512-CB/AGk98u50k42kvgaMM94wzBqozSzDDaonKU7P7jwQIuH2RU0TeBqGYJz2WY1UdihhjweivStrJ2JdkdEmcfw== dependencies: micromark-util-types "^1.0.0" micromark-util-sanitize-uri@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.0.0.tgz#27dc875397cd15102274c6c6da5585d34d4f12b2" integrity sha512-cCxvBKlmac4rxCGx6ejlIviRaMKZc0fWm5HdCHEeDWRSkn44l6NdYVRyU+0nT1XC72EQJMZV8IPHF+jTr56lAg== dependencies: micromark-util-character "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-subtokenize@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.0.tgz#6f006fa719af92776c75a264daaede0fb3943c6a" integrity sha512-EsnG2qscmcN5XhkqQBZni/4oQbLFjz9yk3ZM/P8a3YUjwV6+6On2wehr1ALx0MxK3+XXXLTzuBKHDFeDFYRdgQ== dependencies: micromark-util-chunked "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" micromark-util-symbol@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-symbol/-/micromark-util-symbol-1.0.0.tgz#91cdbcc9b2a827c0129a177d36241bcd3ccaa34d" integrity sha512-NZA01jHRNCt4KlOROn8/bGi6vvpEmlXld7EHcRH+aYWUfL3Wc8JLUNNlqUMKa0hhz6GrpUWsHtzPmKof57v0gQ== micromark-util-types@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/micromark-util-types/-/micromark-util-types-1.0.0.tgz#0ebdfaea3fa7c15fc82b1e06ea1ef0152d0fb2f0" integrity sha512-psf1WAaP1B77WpW4mBGDkTr+3RsPuDAgsvlP47GJzbH1jmjH8xjOx7Z6kp84L8oqHmy5pYO3Ev46odosZV+3AA== micromark@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/micromark/-/micromark-3.0.3.tgz#4c9f76fce8ba68eddf8730bb4fee2041d699d5b7" integrity sha512-fWuHx+JKV4zA8WfCFor2DWP9XmsZkIiyWRGofr7P7IGfpRIlb7/C5wwusGsNyr1D8HI5arghZDG1Ikc0FBwS5Q== dependencies: "@types/debug" "^4.0.0" debug "^4.0.0" micromark-core-commonmark "^1.0.0" micromark-factory-space "^1.0.0" micromark-util-character "^1.0.0" micromark-util-chunked "^1.0.0" micromark-util-combine-extensions "^1.0.0" micromark-util-decode-numeric-character-reference "^1.0.0" micromark-util-encode "^1.0.0" micromark-util-normalize-identifier "^1.0.0" micromark-util-resolve-all "^1.0.0" micromark-util-sanitize-uri "^1.0.0" micromark-util-subtokenize "^1.0.0" micromark-util-symbol "^1.0.0" micromark-util-types "^1.0.0" parse-entities "^3.0.0" micromatch@^4.0.0, micromatch@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259" integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q== dependencies: braces "^3.0.1" picomatch "^2.0.5" [email protected]: version "1.40.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.40.0.tgz#a65057e998db090f732a68f6c276d387d4126c32" integrity sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA== [email protected]: version "1.52.0" resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== mime-types@^2.1.12, mime-types@^2.1.27, mime-types@~2.1.34: version "2.1.35" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== dependencies: mime-db "1.52.0" mime-types@~2.1.24: version "2.1.24" resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.24.tgz#b6f8d0b3e951efb77dedeca194cff6d16f676f81" integrity sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ== dependencies: mime-db "1.40.0" [email protected]: version "1.6.0" resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== mimic-fn@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ== mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== mimic-response@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== mimic-response@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== minimatch@^3.0.2, minimatch@^3.0.4, minimatch@~3.0.4: version "3.0.8" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.8.tgz#5e6a59bd11e2ab0de1cfb843eb2d82e546c321c1" integrity sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q== dependencies: brace-expansion "^1.1.7" minimatch@^5.0.1: version "5.1.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.1.tgz#6c9dffcf9927ff2a31e74b5af11adf8b9604b022" integrity sha512-362NP+zlprccbEt/SkxKfRMHnNY85V74mVnpUpNyr3F35covl09Kec7/sEFLt3RA4oXmewtoaanoIf67SE5Y5g== dependencies: brace-expansion "^2.0.1" minimatch@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.2.tgz#0939d7d6f0898acbd1508abe534d1929368a8fff" integrity sha512-bNH9mmM9qsJ2X4r2Nat1B//1dJVcn3+iBLa3IgqJ7EbGaDNepL9QSHOxN4ng33s52VMMhhIfgCYDk3C4ZmlDAg== dependencies: brace-expansion "^2.0.1" minimist@^1.0.0, minimist@^1.2.5, minimist@^1.2.6, minimist@~1.2.0: version "1.2.6" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== minimist@^1.2.0: version "1.2.7" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== minipass@^3.0.0: version "3.3.6" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw== dependencies: yallist "^4.0.0" minipass@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.1.tgz#2b9408c6e81bb8b338d600fb3685e375a370a057" integrity sha512-V9esFpNbK0arbN3fm2sxDKqMYgIp7XtVdE4Esj+PE4Qaaxdg1wIw48ITQIOn1sc8xXSmUviVL3cyjMqPlrVkiA== minizlib@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" integrity sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg== dependencies: minipass "^3.0.0" yallist "^4.0.0" mkdirp@^0.5.1: version "0.5.5" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== dependencies: minimist "^1.2.5" mkdirp@^1.0.3: version "1.0.4" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== mri@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b" integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA== [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= [email protected], ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== [email protected]: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== nan@nodejs/nan#16fa32231e2ccd89d2804b3f765319128b20c4ac: version "2.15.0" resolved "https://codeload.github.com/nodejs/nan/tar.gz/16fa32231e2ccd89d2804b3f765319128b20c4ac" natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= [email protected]: version "0.6.3" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== neo-async@^2.6.2: version "2.6.2" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== nice-try@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366" integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ== node-fetch@^2.6.1: version "2.6.8" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.8.tgz#a68d30b162bc1d8fd71a367e81b997e1f4d4937e" integrity sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg== dependencies: whatwg-url "^5.0.0" node-fetch@^2.6.7: version "2.6.7" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad" integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ== dependencies: whatwg-url "^5.0.0" node-releases@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503" integrity sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg== normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" resolve "^1.10.0" semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" normalize-path@^3.0.0, normalize-path@~3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== normalize-url@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== npm-run-path@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== dependencies: path-key "^3.0.0" null-loader@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-4.0.0.tgz#8e491b253cd87341d82c0e84b66980d806dfbd04" integrity sha512-vSoBF6M08/RHwc6r0gvB/xBJBtmbvvEkf6+IiadUCoNYchjxE8lwzCGFg0Qp2D25xPiJxUBh2iNWzlzGMILp7Q== dependencies: loader-utils "^2.0.0" schema-utils "^2.6.5" object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= object-inspect@^1.7.0: version "1.8.0" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.8.0.tgz#df807e5ecf53a609cc6bfe93eac3cc7be5b3a9d0" integrity sha512-jLdtEOB112fORuypAyl/50VRVIBIdVQOSUUGQHzJ4xBSbit81zRarz7GThkEFZy1RceYrWYcPcBFPQwHyAc1gA== object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g== object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== object.assign@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== dependencies: define-properties "^1.1.2" function-bind "^1.1.1" has-symbols "^1.0.0" object-keys "^1.0.11" object.entries@^1.1.0: version "1.1.2" resolved "https://registry.yarnpkg.com/object.entries/-/object.entries-1.1.2.tgz#bc73f00acb6b6bb16c203434b10f9a7e797d3add" integrity sha512-BQdB9qKmb/HyNdMNWVr7O3+z5MUIx3aiegEIJqjMBbBf0YT9RRxTJSim4mzFqtyr7PDAHigq0N9dO0m0tRakQA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" has "^1.0.3" object.fromentries@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/object.fromentries/-/object.fromentries-2.0.2.tgz#4a09c9b9bb3843dd0f89acdb517a794d4f355ac9" integrity sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" object.values@^1.1.0, object.values@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object.values/-/object.values-1.1.1.tgz#68a99ecde356b7e9295a3c5e0ce31dc8c953de5e" integrity sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA== dependencies: define-properties "^1.1.3" es-abstract "^1.17.0-next.1" function-bind "^1.1.1" has "^1.0.3" [email protected]: version "2.4.1" resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== dependencies: ee-first "1.1.1" once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" onetime@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" integrity sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ= dependencies: mimic-fn "^1.0.0" onetime@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.0.tgz#fff0f3c91617fe62bb50189636e99ac8a6df7be5" integrity sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q== dependencies: mimic-fn "^2.1.0" optionator@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.3.tgz#84fa1d036fe9d3c7e21d99884b601167ec8fb495" integrity sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA== dependencies: deep-is "~0.1.3" fast-levenshtein "~2.0.6" levn "~0.3.0" prelude-ls "~1.1.2" type-check "~0.3.2" word-wrap "~1.2.3" optionator@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== dependencies: deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" word-wrap "^1.2.3" ora@^3.4.0: version "3.4.0" resolved "https://registry.yarnpkg.com/ora/-/ora-3.4.0.tgz#bf0752491059a3ef3ed4c85097531de9fdbcd318" integrity sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg== dependencies: chalk "^2.4.2" cli-cursor "^2.1.0" cli-spinners "^2.0.0" log-symbols "^2.2.0" strip-ansi "^5.2.0" wcwidth "^1.0.1" ora@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/ora/-/ora-4.0.3.tgz#752a1b7b4be4825546a7a3d59256fa523b6b6d05" integrity sha512-fnDebVFyz309A73cqCipVL1fBZewq4vwgSHfxh43vVy31mbyoQ8sCH3Oeaog/owYOs/lLlGVPCISQonTneg6Pg== dependencies: chalk "^3.0.0" cli-cursor "^3.1.0" cli-spinners "^2.2.0" is-interactive "^1.0.0" log-symbols "^3.0.0" mute-stream "0.0.8" strip-ansi "^6.0.0" wcwidth "^1.0.1" os-tmpdir@^1.0.0, os-tmpdir@~1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= p-cancelable@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== p-limit@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-1.3.0.tgz#b86bd5f0c25690911c7590fcbfc2010d54b3ccb8" integrity sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q== dependencies: p-try "^1.0.0" p-limit@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.2.0.tgz#417c9941e6027a9abcba5092dd2904e255b5fbc2" integrity sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ== dependencies: p-try "^2.0.0" p-limit@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== dependencies: p-try "^2.0.0" p-locate@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" integrity sha1-IKAQOyIqcMj9OcwuWAaA893l7EM= dependencies: p-limit "^1.1.0" p-locate@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-3.0.0.tgz#322d69a05c0264b25997d9f40cd8a891ab0064a4" integrity sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ== dependencies: p-limit "^2.0.0" p-locate@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== dependencies: p-limit "^2.2.0" p-map@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b" integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== dependencies: aggregate-error "^3.0.0" p-try@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-1.0.0.tgz#cbc79cdbaf8fd4228e13f621f2b1a237c1b207b3" integrity sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M= p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== parent-module@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== dependencies: callsites "^3.0.0" parse-entities@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/parse-entities/-/parse-entities-3.0.0.tgz#9ed6d6569b6cfc95ade058d683ddef239dad60dc" integrity sha512-AJlcIFDNPEP33KyJLguv0xJc83BNvjxwpuUIcetyXUsLpVXAUCePJ5kIoYtEN2R1ac0cYaRu/vk9dVFkewHQhQ== dependencies: character-entities "^2.0.0" character-entities-legacy "^2.0.0" character-reference-invalid "^2.0.0" is-alphanumerical "^2.0.0" is-decimal "^2.0.0" is-hexadecimal "^2.0.0" parse-gitignore@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/parse-gitignore/-/parse-gitignore-0.4.0.tgz#abf702e4b900524fff7902b683862857b63f93fe" integrity sha1-q/cC5LkAUk//eQK2g4YoV7Y/k/4= dependencies: array-unique "^0.3.2" is-glob "^3.1.0" parse-json@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= dependencies: error-ex "^1.2.0" parse-json@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= dependencies: error-ex "^1.3.1" json-parse-better-errors "^1.0.1" parse-json@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.0.0.tgz#73e5114c986d143efa3712d4ea24db9a4266f60f" integrity sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw== dependencies: "@babel/code-frame" "^7.0.0" error-ex "^1.3.1" json-parse-better-errors "^1.0.1" lines-and-columns "^1.1.6" parse-ms@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== path-exists@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515" integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU= path-exists@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-key@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" integrity sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A= path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== path-parse@^1.0.6, path-parse@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== [email protected]: version "0.1.7" resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c" integrity sha1-32BBeABfUi8V60SQ5yR6G/qmf4w= path-type@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-2.0.0.tgz#f012ccb8415b7096fc2daa1054c3d72389594c73" integrity sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM= dependencies: pify "^2.0.0" path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== pathval@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pathval/-/pathval-1.1.1.tgz#8534e77a77ce7ac5a2512ea21e0fdb8fcf6c3d8d" integrity sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ== pend@~1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" integrity sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg== picocolors@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== picomatch@^2.0.4, picomatch@^2.0.5: version "2.0.7" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.0.7.tgz#514169d8c7cd0bdbeecc8a2609e34a7163de69f6" integrity sha512-oLHIdio3tZ0qH76NybpeneBhYVj0QFTfXEFTc/B3zKQspYfYYkWYgFsmzo+4kvId/bQRcNkVeguI3y+CD22BtA== picomatch@^2.2.1: version "2.2.2" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== picomatch@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== pify@^2.0.0: version "2.3.0" resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= pify@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== pkg-conf@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pkg-conf/-/pkg-conf-3.1.0.tgz#d9f9c75ea1bae0e77938cde045b276dac7cc69ae" integrity sha512-m0OTbR/5VPNPqO1ph6Fqbj7Hv6QU7gR/tQW40ZqrL1rjgCU85W6C1bJn0BItuJqnR98PWzw7Z8hHeChD1WrgdQ== dependencies: find-up "^3.0.0" load-json-file "^5.2.0" pkg-config@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pkg-config/-/pkg-config-1.1.1.tgz#557ef22d73da3c8837107766c52eadabde298fe4" integrity sha1-VX7yLXPaPIg3EHdmxS6tq94pj+Q= dependencies: debug-log "^1.0.0" find-root "^1.0.0" xtend "^4.0.1" pkg-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-2.0.0.tgz#f6d5d1109e19d63edf428e0bd57e12777615334b" integrity sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s= dependencies: find-up "^2.1.0" pkg-dir@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== dependencies: find-up "^4.0.0" please-upgrade-node@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz#aeddd3f994c933e4ad98b99d9a556efa0e2fe942" integrity sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg== dependencies: semver-compare "^1.0.0" pluralize@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1" integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA== pre-flight@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/pre-flight/-/pre-flight-1.1.1.tgz#482fb1649fb400616a86b2706b11591f5cc8402d" integrity sha512-glqyc2Hh3K+sYeSsVs+HhjyUVf8j6xwuFej0yjYjRYfSnOK8P3Na9GznkoPn48fR+9kTOfkocYIWrtWktp4AqA== dependencies: colors "^1.1.2" commander "^2.9.0" semver "^5.1.0" prelude-ls@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== prelude-ls@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= pretty-ms@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.0.0.tgz#6133a8f55804b208e4728f6aa7bf01085e951e24" integrity sha512-94VRYjL9k33RzfKiGokPBPpsmloBYSf5Ri+Pq19zlsEcUKFob+admeXr5eFDRuPjFmEOcjJvPGdillYOJyvZ7Q== dependencies: parse-ms "^2.1.0" pretty-ms@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-5.1.0.tgz#b906bdd1ec9e9799995c372e2b1c34f073f95384" integrity sha512-4gaK1skD2gwscCfkswYQRmddUb2GJZtzDGRjHWadVHtK/DIKFufa12MvES6/xu1tVbUYeia5bmLcwJtZJQUqnw== dependencies: parse-ms "^2.1.0" process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== process@^0.11.10, process@~0.11.0: version "0.11.10" resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== progress@^2.0.0, progress@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== prop-types@^15.7.2: version "15.7.2" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5" integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ== dependencies: loose-envify "^1.4.0" object-assign "^4.1.1" react-is "^16.8.1" proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg== dependencies: forwarded "0.2.0" ipaddr.js "1.9.1" prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" integrity sha1-0/wRS6BplaRexok/SEzrHXj19HY= psl@^1.1.33: version "1.8.0" resolved "https://registry.yarnpkg.com/psl/-/psl-1.8.0.tgz#9326f8bcfb013adcc005fdff056acce020e51c24" integrity sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ== pump@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== dependencies: end-of-stream "^1.1.0" once "^1.3.1" [email protected]: version "1.3.2" resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.3.2.tgz#9653a036fb7c1ee42342f2325cceefea3926c48d" integrity sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0= punycode@^2.1.0, punycode@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== [email protected]: version "6.11.0" resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q== dependencies: side-channel "^1.0.4" [email protected]: version "0.2.0" resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA= quick-lru@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-5.1.1.tgz#366493e6b3e42a3a6885e2e99d18f80fb7a8c932" integrity sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA== ramda@^0.27.0: version "0.27.0" resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.27.0.tgz#915dc29865c0800bf3f69b8fd6c279898b59de43" integrity sha512-pVzZdDpWwWqEVVLshWUHjNwuVP7SfcmPraYuqocJp1yo2U1R7P+5QAfDhdItkuoGqIBnBYrtPp7rEPqDn9HlZA== randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== dependencies: safe-buffer "^5.1.0" range-parser@~1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== [email protected]: version "2.5.1" resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.1.tgz#fe1b1628b181b700215e5fd42389f98b71392857" integrity sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig== dependencies: bytes "3.1.2" http-errors "2.0.0" iconv-lite "0.4.24" unpipe "1.0.0" react-is@^16.8.1: version "16.8.6" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.8.6.tgz#5bbc1e2d29141c9fbdfed456343fe2bc430a6a16" integrity sha512-aUk3bHfZ2bRSVFFbbeVS4i+lNPZr3/WM5jT2J5omUVV1zzcs1nAaf3l51ctA5FFvCRbhrH0bdAsRRQddFJZPtA== read-pkg-up@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-2.0.0.tgz#6b72a8048984e0c41e79510fd5e9fa99b3b549be" integrity sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4= dependencies: find-up "^2.0.0" read-pkg "^2.0.0" read-pkg@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-2.0.0.tgz#8ef1c0623c6a6db0dc6713c4bfac46332b2368f8" integrity sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg= dependencies: load-json-file "^2.0.0" normalize-package-data "^2.3.2" path-type "^2.0.0" readable-stream@^2, readable-stream@^2.0.1, readable-stream@~2.3.6: version "2.3.6" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" isarray "~1.0.0" process-nextick-args "~2.0.0" safe-buffer "~5.1.1" string_decoder "~1.1.1" util-deprecate "~1.0.1" readable-stream@^3.0.2: version "3.6.0" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== dependencies: inherits "^2.0.3" string_decoder "^1.1.1" util-deprecate "^1.0.1" readdirp@~3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7" integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA== dependencies: picomatch "^2.2.1" rechoir@^0.6.2: version "0.6.2" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= dependencies: resolve "^1.1.6" rechoir@^0.7.0: version "0.7.1" resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== dependencies: resolve "^1.9.0" regexpp@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-2.0.1.tgz#8d19d31cf632482b589049f8281f93dbcba4d07f" integrity sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw== regexpp@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.0.0.tgz#dd63982ee3300e67b41c1956f850aa680d9d330e" integrity sha512-Z+hNr7RAVWxznLPuA7DIh8UNX1j9CDrUQxskw9IrBE1Dxue2lyXT+shqEIeLUjrokxIP8CMy1WkjgG3rTsd5/g== regexpp@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== remark-cli@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-cli/-/remark-cli-10.0.0.tgz#3b0e20f2ad3909f35c7a6fb3f721c82f6ff5beac" integrity sha512-Yc5kLsJ5vgiQJl6xMLLJHqPac6OSAC5DOqKQrtmzJxSdJby2Jgr+OpIAkWQYwvbNHEspNagyoQnuwK2UCWg73g== dependencies: remark "^14.0.0" unified-args "^9.0.0" remark-lint-blockquote-indentation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-blockquote-indentation/-/remark-lint-blockquote-indentation-2.0.1.tgz#27347959acf42a6c3e401488d8210e973576b254" integrity sha512-uJ9az/Ms9AapnkWpLSCJfawBfnBI2Tn1yUsPNqIFv6YM98ymetItUMyP6ng9NFPqDvTQBbiarulkgoEo0wcafQ== dependencies: mdast-util-to-string "^1.0.2" pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-code-block-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-code-block-style/-/remark-lint-code-block-style-2.0.1.tgz#448b0f2660acfcdfff2138d125ff5b1c1279c0cb" integrity sha512-eRhmnColmSxJhO61GHZkvO67SpHDshVxs2j3+Zoc5Y1a4zQT2133ZAij04XKaBFfsVLjhbY/+YOWxgvtjx2nmA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-case@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-case/-/remark-lint-definition-case-2.0.1.tgz#10340eb2f87acff41140d52ad7e5b40b47e6690a" integrity sha512-M+XlThtQwEJLQnQb5Gi6xZdkw92rGp7m2ux58WMw/Qlcg02WgHR/O0OcHPe5VO5hMJrtI+cGG5T0svsCgRZd3w== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-definition-spacing@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-definition-spacing/-/remark-lint-definition-spacing-2.0.1.tgz#97f01bf9bf77a7bdf8013b124b7157dd90b07c64" integrity sha512-xK9DOQO5MudITD189VyUiMHBIKltW1oc55L7Fti3i9DedXoBG7Phm+V9Mm7IdWzCVkquZVgVk63xQdqzSQRrSQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-emphasis-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-emphasis-marker/-/remark-lint-emphasis-marker-2.0.1.tgz#1d5ca2070d4798d16c23120726158157796dc317" integrity sha512-7mpbAUrSnHiWRyGkbXRL5kfSKY9Cs8cdob7Fw+Z02/pufXMF4yRWaegJ5NTUu1RE+SKlF44wtWWjvcIoyY6/aw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-flag@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-flag/-/remark-lint-fenced-code-flag-2.0.1.tgz#2cb3ddb1157082c45760c7d01ca08e13376aaf62" integrity sha512-+COnWHlS/h02FMxoZWxNlZW3Y8M0cQQpmx3aNCbG7xkyMyCKsMLg9EmRvYHHIbxQCuF3JT0WWx5AySqlc7d+NA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-fenced-code-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-fenced-code-marker/-/remark-lint-fenced-code-marker-2.0.1.tgz#7bbeb0fb45b0818a3c8a2d232cf0c723ade58ecf" integrity sha512-lujpjm04enn3ma6lITlttadld6eQ1OWAEcT3qZzvFHp+zPraC0yr0eXlvtDN/0UH8mrln/QmGiZp3i8IdbucZg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-file-extension@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-file-extension/-/remark-lint-file-extension-1.0.3.tgz#a7fc78fbf041e513c618b2cca0f2160ee37daa13" integrity sha512-P5gzsxKmuAVPN7Kq1W0f8Ss0cFKfu+OlezYJWXf+5qOa+9Y5GqHEUOobPnsmNFZrVMiM7JoqJN2C9ZjrUx3N6Q== dependencies: unified-lint-rule "^1.0.0" remark-lint-final-definition@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/remark-lint-final-definition/-/remark-lint-final-definition-2.1.0.tgz#b6e654c01ebcb1afc936d7b9cd74db8ec273e0bb" integrity sha512-83K7n2icOHPfBzbR5Mr1o7cu8gOjD8FwJkFx/ly+rW+8SHfjCj4D3WOFGQ1xVdmHjfomBDXXDSNo2oiacADVXQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-hard-break-spaces@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-hard-break-spaces/-/remark-lint-hard-break-spaces-2.0.1.tgz#2149b55cda17604562d040c525a2a0d26aeb0f0f" integrity sha512-Qfn/BMQFamHhtbfLrL8Co/dbYJFLRL4PGVXZ5wumkUO5f9FkZC2RsV+MD9lisvGTkJK0ZEJrVVeaPbUIFM0OAw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-heading-increment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-increment/-/remark-lint-heading-increment-2.0.1.tgz#b578f251508a05d79bc2d1ae941e0620e23bf1d3" integrity sha512-bYDRmv/lk3nuWXs2VSD1B4FneGT6v7a74FuVmb305hyEMmFSnneJvVgnOJxyKlbNlz12pq1IQ6MhlJBda/SFtQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-heading-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-heading-style/-/remark-lint-heading-style-2.0.1.tgz#8216fca67d97bbbeec8a19b6c71bfefc16549f72" integrity sha512-IrFLNs0M5Vbn9qg51AYhGUfzgLAcDOjh2hFGMz3mx664dV6zLcNZOPSdJBBJq3JQR4gKpoXcNwN1+FFaIATj+A== dependencies: mdast-util-heading-style "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-link-title-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-link-title-style/-/remark-lint-link-title-style-2.0.1.tgz#51a595c69fcfa73a245a030dfaa3504938a1173a" integrity sha512-+Q7Ew8qpOQzjqbDF6sUHmn9mKgje+m2Ho8Xz7cEnGIRaKJgtJzkn/dZqQM/az0gn3zaN6rOuwTwqw4EsT5EsIg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-list-item-content-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-content-indent/-/remark-lint-list-item-content-indent-2.0.1.tgz#96387459440dcd61e522ab02bff138b32bfaa63a" integrity sha512-OzUMqavxyptAdG7vWvBSMc9mLW9ZlTjbW4XGayzczd3KIr6Uwp3NEFXKx6MLtYIM/vwBqMrPQUrObOC7A2uBpQ== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-indent@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-list-item-indent/-/remark-lint-list-item-indent-2.0.1.tgz#c6472514e17bc02136ca87936260407ada90bf8d" integrity sha512-4IKbA9GA14Q9PzKSQI6KEHU/UGO36CSQEjaDIhmb9UOhyhuzz4vWhnSIsxyI73n9nl9GGRAMNUSGzr4pQUFwTA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-list-item-spacing@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-list-item-spacing/-/remark-lint-list-item-spacing-3.0.0.tgz#14c18fe8c0f19231edb5cf94abda748bb773110b" integrity sha512-SRUVonwdN3GOSFb6oIYs4IfJxIVR+rD0nynkX66qEO49/qDDT1PPvkndis6Nyew5+t+2V/Db9vqllL6SWbnEtw== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-maximum-heading-length@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-maximum-heading-length/-/remark-lint-maximum-heading-length-2.0.1.tgz#56f240707a75b59bce3384ccc9da94548affa98f" integrity sha512-1CjJ71YDqEpoOjUnc4wrwZV8ZGXWUIYRYeGoarAy3QKHepJL9M+zkdbOxZDfhc3tjVoDW/LWcgsW+DEpczgiMA== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-maximum-line-length@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/remark-lint-maximum-line-length/-/remark-lint-maximum-line-length-2.0.3.tgz#d0d15410637d61b031a83d7c78022ec46d6c858a" integrity sha512-zyWHBFh1oPAy+gkaVFXiTHYP2WwriIeBtaarDqkweytw0+qmuikjVMJTWbQ3+XfYBreD7KKDM9SI79nkp0/IZQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-auto-link-without-protocol@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-auto-link-without-protocol/-/remark-lint-no-auto-link-without-protocol-2.0.1.tgz#f75e5c24adb42385593e0d75ca39987edb70b6c4" integrity sha512-TFcXxzucsfBb/5uMqGF1rQA+WJJqm1ZlYQXyvJEXigEZ8EAxsxZGPb/gOQARHl/y0vymAuYxMTaChavPKaBqpQ== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-blockquote-without-marker@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-blockquote-without-marker/-/remark-lint-no-blockquote-without-marker-4.0.0.tgz#856fb64dd038fa8fc27928163caa24a30ff4d790" integrity sha512-Y59fMqdygRVFLk1gpx2Qhhaw5IKOR9T38Wf7pjR07bEFBGUNfcoNVIFMd1TCJfCPQxUyJzzSqfZz/KT7KdUuiQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-no-consecutive-blank-lines@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-consecutive-blank-lines/-/remark-lint-no-consecutive-blank-lines-3.0.0.tgz#c8fe11095b8f031a1406da273722bd4a9174bf41" integrity sha512-kmzLlOLrapBKEngwYFTdCZDmeOaze6adFPB7G0EdymD9V1mpAlnneINuOshRLEDKK5fAhXKiZXxdGIaMPkiXrA== dependencies: pluralize "^8.0.0" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-duplicate-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-duplicate-headings/-/remark-lint-no-duplicate-headings-2.0.1.tgz#4a4b70e029155ebcfc03d8b2358c427b69a87576" integrity sha512-F6AP0FJcHIlkmq0pHX0J5EGvLA9LfhuYTvnNO8y3kvflHeRjFkDyt2foz/taXR8OcLQR51n/jIJiwrrSMbiauw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-emphasis-as-heading@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-emphasis-as-heading/-/remark-lint-no-emphasis-as-heading-2.0.1.tgz#fcc064133fe00745943c334080fed822f72711ea" integrity sha512-z86+yWtVivtuGIxIC4g9RuATbgZgOgyLcnaleonJ7/HdGTYssjJNyqCJweaWSLoaI0akBQdDwmtJahW5iuX3/g== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-file-name-articles@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-articles/-/remark-lint-no-file-name-articles-1.0.3.tgz#c712d06a24e24b0c4c3666cf3084a0052a2c2c17" integrity sha512-YZDJDKUWZEmhrO6tHB0u0K0K2qJKxyg/kryr14OaRMvWLS62RgMn97sXPZ38XOSN7mOcCnl0k7/bClghJXx0sg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-consecutive-dashes@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-consecutive-dashes/-/remark-lint-no-file-name-consecutive-dashes-1.0.3.tgz#6a96ddf60e18dcdb004533733f3ccbfd8ab076ae" integrity sha512-7f4vyXn/ca5lAguWWC3eu5hi8oZ7etX7aQlnTSgQZeslnJCbVJm6V6prFJKAzrqbBzMicUXr5pZLBDoXyTvHHw== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-irregular-characters@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-irregular-characters/-/remark-lint-no-file-name-irregular-characters-1.0.3.tgz#6dcd8b51e00e10094585918cb8e7fc999df776c3" integrity sha512-b4xIy1Yi8qZpM2vnMN+6gEujagPGxUBAs1judv6xJQngkl5d5zT8VQZsYsTGHku4NWHjjh3b7vK5mr0/yp4JSg== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-mixed-case@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-mixed-case/-/remark-lint-no-file-name-mixed-case-1.0.3.tgz#0ebe5eedd0191507d27ad6ac5eed1778cb33c2de" integrity sha512-d7rJ4c8CzDbEbGafw2lllOY8k7pvnsO77t8cV4PHFylwQ3hmCdTHLuDvK87G3DaWCeKclp0PMyamfOgJWKMkPA== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-file-name-outer-dashes@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/remark-lint-no-file-name-outer-dashes/-/remark-lint-no-file-name-outer-dashes-1.0.4.tgz#c6e22a5cc64df4e12fc31712a927e8039854a666" integrity sha512-+bZvvme2Bm3Vp5L2iKuvGHYVmHKrTkkRt8JqJPGepuhvBvT4Q7+CgfKyMtC/hIjyl+IcuJQ2H0qPRzdicjy1wQ== dependencies: unified-lint-rule "^1.0.0" remark-lint-no-heading-punctuation@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-heading-punctuation/-/remark-lint-no-heading-punctuation-2.0.1.tgz#face59f9a95c8aa278a8ee0c728bc44cd53ea9ed" integrity sha512-lY/eF6GbMeGu4cSuxfGHyvaQQBIq/6T/o+HvAR5UfxSTxmxZFwbZneAI2lbeR1zPcqOU87NsZ5ZZzWVwdLpPBw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-inline-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-inline-padding/-/remark-lint-no-inline-padding-3.0.0.tgz#14c2722bcddc648297a54298107a922171faf6eb" integrity sha512-3s9uW3Yux9RFC0xV81MQX3bsYs+UY7nPnRuMxeIxgcVwxQ4E/mTJd9QjXUwBhU9kdPtJ5AalngdmOW2Tgar8Cg== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-literal-urls@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-literal-urls/-/remark-lint-no-literal-urls-2.0.1.tgz#731908f9866c1880e6024dcee1269fb0f40335d6" integrity sha512-IDdKtWOMuKVQIlb1CnsgBoyoTcXU3LppelDFAIZePbRPySVHklTtuK57kacgU5grc7gPM04bZV96eliGrRU7Iw== dependencies: mdast-util-to-string "^1.0.2" unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-no-multiple-toplevel-headings@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-multiple-toplevel-headings/-/remark-lint-no-multiple-toplevel-headings-2.0.1.tgz#3ff2b505adf720f4ff2ad2b1021f8cfd50ad8635" integrity sha512-VKSItR6c+u3OsE5pUiSmNusERNyQS9Nnji26ezoQ1uvy06k3RypIjmzQqJ/hCkSiF+hoyC3ibtrrGT8gorzCmQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-stringify-position "^2.0.0" unist-util-visit "^2.0.0" remark-lint-no-shell-dollars@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/remark-lint-no-shell-dollars/-/remark-lint-no-shell-dollars-2.0.2.tgz#b2c6c3ed95e5615f8e5f031c7d271a18dc17618e" integrity sha512-zhkHZOuyaD3r/TUUkkVqW0OxsR9fnSrAnHIF63nfJoAAUezPOu8D1NBsni6rX8H2DqGbPYkoeWrNsTwiKP0yow== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-image@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-image/-/remark-lint-no-shortcut-reference-image-2.0.1.tgz#d174d12a57e8307caf6232f61a795bc1d64afeaa" integrity sha512-2jcZBdnN6ecP7u87gkOVFrvICLXIU5OsdWbo160FvS/2v3qqqwF2e/n/e7D9Jd+KTq1mR1gEVVuTqkWWuh3cig== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-shortcut-reference-link@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-no-shortcut-reference-link/-/remark-lint-no-shortcut-reference-link-2.0.1.tgz#8f963f81036e45cfb7061b3639e9c6952308bc94" integrity sha512-pTZbslG412rrwwGQkIboA8wpBvcjmGFmvugIA+UQR+GfFysKtJ5OZMPGJ98/9CYWjw9Z5m0/EktplZ5TjFjqwA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-visit "^2.0.0" remark-lint-no-table-indentation@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-no-table-indentation/-/remark-lint-no-table-indentation-3.0.0.tgz#f3c3fc24375069ec8e510f43050600fb22436731" integrity sha512-+l7GovI6T+3LhnTtz/SmSRyOb6Fxy6tmaObKHrwb/GAebI/4MhFS1LVo3vbiP/RpPYtyQoFbbuXI55hqBG4ibQ== dependencies: unified-lint-rule "^1.0.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" vfile-location "^3.0.0" remark-lint-ordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-style/-/remark-lint-ordered-list-marker-style-2.0.1.tgz#183c31967e6f2ae8ef00effad03633f7fd00ffaa" integrity sha512-Cnpw1Dn9CHn+wBjlyf4qhPciiJroFOEGmyfX008sQ8uGoPZsoBVIJx76usnHklojSONbpjEDcJCjnOvfAcWW1A== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-ordered-list-marker-value@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-ordered-list-marker-value/-/remark-lint-ordered-list-marker-value-2.0.1.tgz#0de343de2efb41f01eae9f0f7e7d30fe43db5595" integrity sha512-blt9rS7OKxZ2NW8tqojELeyNEwPhhTJGVa+YpUkdEH+KnrdcD7Nzhnj6zfLWOx6jFNZk3jpq5nvLFAPteHaNKg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-rule-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-rule-style/-/remark-lint-rule-style-2.0.1.tgz#f59bd82e75d3eaabd0eee1c8c0f5513372eb553c" integrity sha512-hz4Ff9UdlYmtO6Czz99WJavCjqCer7Cav4VopXt+yVIikObw96G5bAuLYcVS7hvMUGqC9ZuM02/Y/iq9n8pkAg== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-strong-marker@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-strong-marker/-/remark-lint-strong-marker-2.0.1.tgz#1ad8f190c6ac0f8138b638965ccf3bcd18f6d4e4" integrity sha512-8X2IsW1jZ5FmW9PLfQjkL0OVy/J3xdXLcZrG1GTeQKQ91BrPFyEZqUM2oM6Y4S6LGtxWer+neZkPZNroZoRPBQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-cell-padding@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-cell-padding/-/remark-lint-table-cell-padding-3.0.0.tgz#a769ba1999984ff5f90294fb6ccb8aead7e8a12f" integrity sha512-sEKrbyFZPZpxI39R8/r+CwUrin9YtyRwVn0SQkNQEZWZcIpylK+bvoKIldvLIXQPob+ZxklL0GPVRzotQMwuWQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipe-alignment@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-table-pipe-alignment/-/remark-lint-table-pipe-alignment-2.0.1.tgz#12b7e4c54473d69c9866cb33439c718d09cffcc5" integrity sha512-O89U7bp0ja6uQkT2uQrNB76GaPvFabrHiUGhqEUnld21yEdyj7rgS57kn84lZNSuuvN1Oor6bDyCwWQGzzpoOQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-table-pipes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/remark-lint-table-pipes/-/remark-lint-table-pipes-3.0.0.tgz#b30b055d594cae782667eec91c6c5b35928ab259" integrity sha512-QPokSazEdl0Y8ayUV9UB0Ggn3Jos/RAQwIo0z1KDGnJlGDiF80Jc6iU9RgDNUOjlpQffSLIfSVxH5VVYF/K3uQ== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint-unordered-list-marker-style@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/remark-lint-unordered-list-marker-style/-/remark-lint-unordered-list-marker-style-2.0.1.tgz#e64692aa9594dbe7e945ae76ab2218949cd92477" integrity sha512-8KIDJNDtgbymEvl3LkrXgdxPMTOndcux3BHhNGB2lU4UnxSpYeHsxcDgirbgU6dqCAfQfvMjPvfYk19QTF9WZA== dependencies: unified-lint-rule "^1.0.0" unist-util-generated "^1.1.0" unist-util-position "^3.0.0" unist-util-visit "^2.0.0" remark-lint@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/remark-lint/-/remark-lint-8.0.0.tgz#6e40894f4a39eaea31fc4dd45abfaba948bf9a09" integrity sha512-ESI8qJQ/TIRjABDnqoFsTiZntu+FRifZ5fJ77yX63eIDijl/arvmDvT+tAf75/Nm5BFL4R2JFUtkHRGVjzYUsg== dependencies: remark-message-control "^6.0.0" remark-message-control@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/remark-message-control/-/remark-message-control-6.0.0.tgz#955b054b38c197c9f2e35b1d88a4912949db7fc5" integrity sha512-k9bt7BYc3G7YBdmeAhvd3VavrPa/XlKWR3CyHjr4sLO9xJyly8WHHT3Sp+8HPR8lEUv+/sZaffL7IjMLV0f6BA== dependencies: mdast-comment-marker "^1.0.0" unified-message-control "^3.0.0" remark-parse@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-parse/-/remark-parse-10.0.0.tgz#65e2b2b34d8581d36b97f12a2926bb2126961cb4" integrity sha512-07ei47p2Xl7Bqbn9H2VYQYirnAFJPwdMuypdozWsSbnmrkgA2e2sZLZdnDNrrsxR4onmIzH/J6KXqKxCuqHtPQ== dependencies: "@types/mdast" "^3.0.0" mdast-util-from-markdown "^1.0.0" unified "^10.0.0" remark-preset-lint-markdown-style-guide@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/remark-preset-lint-markdown-style-guide/-/remark-preset-lint-markdown-style-guide-4.0.0.tgz#976b6ffd7f37aa90868e081a69241fcde3a297d4" integrity sha512-gczDlfZ28Fz0IN/oddy0AH4CiTu9S8d3pJWUsrnwFiafjhJjPGobGE1OD3bksi53md1Bp4K0fzo99YYfvB4Sjw== dependencies: remark-lint "^8.0.0" remark-lint-blockquote-indentation "^2.0.0" remark-lint-code-block-style "^2.0.0" remark-lint-definition-case "^2.0.0" remark-lint-definition-spacing "^2.0.0" remark-lint-emphasis-marker "^2.0.0" remark-lint-fenced-code-flag "^2.0.0" remark-lint-fenced-code-marker "^2.0.0" remark-lint-file-extension "^1.0.0" remark-lint-final-definition "^2.0.0" remark-lint-hard-break-spaces "^2.0.0" remark-lint-heading-increment "^2.0.0" remark-lint-heading-style "^2.0.0" remark-lint-link-title-style "^2.0.0" remark-lint-list-item-content-indent "^2.0.0" remark-lint-list-item-indent "^2.0.0" remark-lint-list-item-spacing "^3.0.0" remark-lint-maximum-heading-length "^2.0.0" remark-lint-maximum-line-length "^2.0.0" remark-lint-no-auto-link-without-protocol "^2.0.0" remark-lint-no-blockquote-without-marker "^4.0.0" remark-lint-no-consecutive-blank-lines "^3.0.0" remark-lint-no-duplicate-headings "^2.0.0" remark-lint-no-emphasis-as-heading "^2.0.0" remark-lint-no-file-name-articles "^1.0.0" remark-lint-no-file-name-consecutive-dashes "^1.0.0" remark-lint-no-file-name-irregular-characters "^1.0.0" remark-lint-no-file-name-mixed-case "^1.0.0" remark-lint-no-file-name-outer-dashes "^1.0.0" remark-lint-no-heading-punctuation "^2.0.0" remark-lint-no-inline-padding "^3.0.0" remark-lint-no-literal-urls "^2.0.0" remark-lint-no-multiple-toplevel-headings "^2.0.0" remark-lint-no-shell-dollars "^2.0.0" remark-lint-no-shortcut-reference-image "^2.0.0" remark-lint-no-shortcut-reference-link "^2.0.0" remark-lint-no-table-indentation "^3.0.0" remark-lint-ordered-list-marker-style "^2.0.0" remark-lint-ordered-list-marker-value "^2.0.0" remark-lint-rule-style "^2.0.0" remark-lint-strong-marker "^2.0.0" remark-lint-table-cell-padding "^3.0.0" remark-lint-table-pipe-alignment "^2.0.0" remark-lint-table-pipes "^3.0.0" remark-lint-unordered-list-marker-style "^2.0.0" remark-stringify@^10.0.0: version "10.0.0" resolved "https://registry.yarnpkg.com/remark-stringify/-/remark-stringify-10.0.0.tgz#7f23659d92b2d5da489e3c858656d7bbe045f161" integrity sha512-3LAQqJ/qiUxkWc7fUcVuB7RtIT38rvmxfmJG8z1TiE/D8zi3JGQ2tTcTJu9Tptdpb7gFwU0whRi5q1FbFOb9yA== dependencies: "@types/mdast" "^3.0.0" mdast-util-to-markdown "^1.0.0" unified "^10.0.0" remark@^14.0.0: version "14.0.1" resolved "https://registry.yarnpkg.com/remark/-/remark-14.0.1.tgz#a97280d4f2a3010a7d81e6c292a310dcd5554d80" integrity sha512-7zLG3u8EUjOGuaAS9gUNJPD2j+SqDqAFHv2g6WMpE5CU9rZ6e3IKDM12KHZ3x+YNje+NMAuN55yx8S5msGSx7Q== dependencies: "@types/mdast" "^3.0.0" remark-parse "^10.0.0" remark-stringify "^10.0.0" unified "^10.0.0" repeat-string@^1.0.0: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= requireindex@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/requireindex/-/requireindex-1.1.0.tgz#e5404b81557ef75db6e49c5a72004893fe03e162" integrity sha1-5UBLgVV+91225JxacgBIk/4D4WI= resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" integrity sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g== resolve-cwd@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== dependencies: resolve-from "^5.0.0" resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== resolve-from@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== resolve@^1.1.6: version "1.21.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.21.0.tgz#b51adc97f3472e6a5cf4444d34bc9d6b9037591f" integrity sha512-3wCbTpk5WJlyE4mSOtDLhqQmGFi0/TD9VPwmiolnk8U0wRgMEktqCXd3vy5buTO3tljvalNvKrjHEfrd2WpEKA== dependencies: is-core-module "^2.8.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" resolve@^1.10.0: version "1.11.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.11.1.tgz#ea10d8110376982fef578df8fc30b9ac30a07a3e" integrity sha512-vIpgF6wfuJOZI7KKKSP+HmiKggadPQAdsp5HiC1mvqnfp0gF1vdwgBWZIdrVft9pgqoMFQN+R7BSWZiBxx+BBw== dependencies: path-parse "^1.0.6" resolve@^1.10.1, resolve@^1.11.0, resolve@^1.13.1, resolve@^1.17.0: version "1.17.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== dependencies: path-parse "^1.0.6" resolve@^1.9.0: version "1.22.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177" integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw== dependencies: is-core-module "^2.9.0" path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" responselike@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/responselike/-/responselike-2.0.0.tgz#26391bcc3174f750f9a79eacc40a12a5c42d7723" integrity sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw== dependencies: lowercase-keys "^2.0.0" restore-cursor@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" integrity sha1-n37ih/gv0ybU/RYpI9YhKe7g368= dependencies: onetime "^2.0.0" signal-exit "^3.0.2" restore-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== dependencies: onetime "^5.1.0" signal-exit "^3.0.2" reusify@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== [email protected]: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" integrity sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA== dependencies: glob "^7.1.3" rimraf@~2.2.6: version "2.2.8" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.2.8.tgz#e439be2aaee327321952730f99a8929e4fc50582" integrity sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI= roarr@^2.15.3: version "2.15.4" resolved "https://registry.yarnpkg.com/roarr/-/roarr-2.15.4.tgz#f5fe795b7b838ccfe35dc608e0282b9eba2e7afd" integrity sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A== dependencies: boolean "^3.0.1" detect-node "^2.0.4" globalthis "^1.0.1" json-stringify-safe "^5.0.1" semver-compare "^1.0.0" sprintf-js "^1.1.2" run-async@^2.4.0: version "2.4.1" resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" integrity sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ== run-con@~1.2.11: version "1.2.11" resolved "https://registry.yarnpkg.com/run-con/-/run-con-1.2.11.tgz#0014ed430bad034a60568dfe7de2235f32e3f3c4" integrity sha512-NEMGsUT+cglWkzEr4IFK21P4Jca45HqiAbIIZIBdX5+UZTB24Mb/21iNGgz9xZa8tL6vbW7CXmq7MFN42+VjNQ== dependencies: deep-extend "^0.6.0" ini "~3.0.0" minimist "^1.2.6" strip-json-comments "~3.1.1" run-parallel@^1.1.2, run-parallel@^1.1.9: version "1.1.9" resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.1.9.tgz#c9dd3a7cf9f4b2c4b6244e173a6ed866e61dd679" integrity sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q== rxjs@^6.5.5, rxjs@^6.6.0: version "6.6.0" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-6.6.0.tgz#af2901eedf02e3a83ffa7f886240ff9018bbec84" integrity sha512-3HMA8z/Oz61DUHe+SdOiQyzIf4tOx5oQHmMir7IZEu6TMqCLHT4LRcmNaUS0NwOz8VLvmmBduMsoaUvMaIiqzg== dependencies: tslib "^1.9.0" sade@^1.7.3: version "1.8.1" resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701" integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A== dependencies: mri "^1.1.0" [email protected], safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== "safer-buffer@>= 2.1.2 < 3": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== [email protected]: version "1.2.1" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.1.tgz#7b8e656190b228e81a66aea748480d828cd2d37a" integrity sha1-e45lYZCyKOgaZq6nSEgNgozS03o= sax@>=0.6.0: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== schema-utils@^2.6.5: version "2.7.0" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.7.0.tgz#17151f76d8eae67fbbf77960c33c676ad9f4efc7" integrity sha512-0ilKFI6QQF5nxDZLFn2dMjvc4hjg/Wkg7rHd3jK6/A4a1Hl9VFdQWvgB1UMGoU94pad1P/8N7fMcEnLnSiju8A== dependencies: "@types/json-schema" "^7.0.4" ajv "^6.12.2" ajv-keywords "^3.4.1" schema-utils@^3.1.0, schema-utils@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-3.1.1.tgz#bc74c4b6b6995c1d88f76a8b77bea7219e0c8281" integrity sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw== dependencies: "@types/json-schema" "^7.0.8" ajv "^6.12.5" ajv-keywords "^3.5.2" semver-compare@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/semver-compare/-/semver-compare-1.0.0.tgz#0dee216a1c941ab37e9efb1788f6afc5ff5537fc" integrity sha1-De4hahyUGrN+nvsXiPavxf9VN/w= "semver@2 || 3 || 4 || 5", semver@^5.6.0: version "5.7.0" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.0.tgz#790a7cf6fea5459bac96110b29b60412dc8ff96b" integrity sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA== semver@^5.1.0, semver@^5.5.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== semver@^6.0.0: version "6.2.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.2.0.tgz#4d813d9590aaf8a9192693d6c85b9344de5901db" integrity sha512-jdFC1VdUGT/2Scgbimf7FSx9iJLXoqfglSF+gJeuNWVpiE37OIbc1jywR/GJyFdz3mnkz2/id0L0J/cr0izR5A== semver@^6.1.0, semver@^6.1.2, semver@^6.2.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== semver@^7.0.0: version "7.3.5" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.5.tgz#0b621c879348d8998e4b0e4be94b3f12e6018ef7" integrity sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ== dependencies: lru-cache "^6.0.0" semver@^7.2.1, semver@^7.3.2: version "7.3.2" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.2.tgz#604962b052b81ed0786aae84389ffba70ffd3938" integrity sha512-OrOb32TeeambH6UrhtShmF7CRDqhL6/5XpPNp2DuRH6+9QLw/orhp72j87v8Qa1ScDkvrrBNpZcDejAirJmfXQ== semver@^7.3.5, semver@^7.3.8: version "7.3.8" resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== dependencies: lru-cache "^6.0.0" [email protected]: version "0.18.0" resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be" integrity sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg== dependencies: debug "2.6.9" depd "2.0.0" destroy "1.2.0" encodeurl "~1.0.2" escape-html "~1.0.3" etag "~1.8.1" fresh "0.5.2" http-errors "2.0.0" mime "1.6.0" ms "2.1.3" on-finished "2.4.1" range-parser "~1.2.1" statuses "2.0.1" serialize-error@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/serialize-error/-/serialize-error-7.0.1.tgz#f1360b0447f61ffb483ec4157c737fab7d778e18" integrity sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw== dependencies: type-fest "^0.13.1" serialize-javascript@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== dependencies: randombytes "^2.1.0" [email protected]: version "1.15.0" resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.15.0.tgz#faaef08cffe0a1a62f60cad0c4e513cff0ac9540" integrity sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g== dependencies: encodeurl "~1.0.2" escape-html "~1.0.3" parseurl "~1.3.3" send "0.18.0" [email protected]: version "1.2.0" resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== shallow-clone@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== dependencies: kind-of "^6.0.2" shebang-command@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" integrity sha1-RKrGW2lbAzmJaMOfNj/uXer98eo= dependencies: shebang-regex "^1.0.0" shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== dependencies: shebang-regex "^3.0.0" shebang-regex@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" integrity sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM= shebang-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== shelljs@^0.8.1: version "0.8.5" resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.8.5.tgz#de055408d8361bed66c669d2f000538ced8ee20c" integrity sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow== dependencies: glob "^7.0.0" interpret "^1.0.0" rechoir "^0.6.2" shx@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/shx/-/shx-0.3.2.tgz#40501ce14eb5e0cbcac7ddbd4b325563aad8c123" integrity sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA== dependencies: es6-object-assign "^1.0.3" minimist "^1.2.0" shelljs "^0.8.1" side-channel@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== dependencies: call-bind "^1.0.0" get-intrinsic "^1.0.2" object-inspect "^1.9.0" signal-exit@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.3.tgz#a1410c2edd8f077b08b4e253c8eacfcaf057461c" integrity sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA== simple-git@^3.5.0: version "3.16.0" resolved "https://registry.yarnpkg.com/simple-git/-/simple-git-3.16.0.tgz#421773e24680f5716999cc4a1d60127b4b6a9dec" integrity sha512-zuWYsOLEhbJRWVxpjdiXl6eyAyGo/KzVW+KFhhw9MqEEJttcq+32jTWSGyxTdf9e/YCohxRE+9xpWFj9FdiJNw== dependencies: "@kwsites/file-exists" "^1.1.1" "@kwsites/promise-deferred" "^1.1.1" debug "^4.3.4" slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== slice-ansi@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-2.1.0.tgz#cacd7693461a637a5788d92a7dd4fba068e81636" integrity sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ== dependencies: ansi-styles "^3.2.0" astral-regex "^1.0.0" is-fullwidth-code-point "^2.0.0" slice-ansi@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" slice-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== dependencies: ansi-styles "^4.0.0" astral-regex "^2.0.0" is-fullwidth-code-point "^3.0.0" sliced@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/sliced/-/sliced-1.0.1.tgz#0b3a662b5d04c3177b1926bea82b03f837a2ef41" integrity sha1-CzpmK10Ewxd7GSa+qCsD+Dei70E= source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== dependencies: buffer-from "^1.0.0" source-map "^0.6.0" source-map@^0.6.0: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== spdx-correct@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== spdx-expression-parse@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: version "3.0.4" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz#75ecd1a88de8c184ef015eafb51b5b48bfd11bb1" integrity sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA== sprintf-js@^1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.2.tgz#da1765262bf8c0f571749f2ad6c26300207ae673" integrity sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug== sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= standard-engine@^12.0.0: version "12.1.0" resolved "https://registry.yarnpkg.com/standard-engine/-/standard-engine-12.1.0.tgz#b13dbae583de54c06805207b991ef48a582c0e62" integrity sha512-DVJnWM1CGkag4ucFLGdiYWa5/kJURPONmMmk17p8FT5NE4UnPZB1vxWnXnRo2sPSL78pWJG8xEM+1Tu19z0deg== dependencies: deglob "^4.0.1" get-stdin "^7.0.0" minimist "^1.2.5" pkg-conf "^3.1.0" standard-markdown@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/standard-markdown/-/standard-markdown-6.0.0.tgz#bb7519a86275900eaa7a951d98937723c7010ed6" integrity sha512-9lQs4ZfGukyalFVputnN4IxfbMIAECjf+BqC4gvY8eBUvYcotYIWj4MZyMiXBkN/OJwmMi5jVSnzIexKZQqQYA== dependencies: commander "^4.1.0" globby "^11.0.0" lodash.flatten "^4.4.0" lodash.range "^3.2.0" ora "^4.0.3" standard "^14.3.1" standard@^14.3.1: version "14.3.4" resolved "https://registry.yarnpkg.com/standard/-/standard-14.3.4.tgz#748e80e8cd7b535844a85a12f337755a7e3a0f6e" integrity sha512-+lpOkFssMkljJ6eaILmqxHQ2n4csuEABmcubLTb9almFi1ElDzXb1819fjf/5ygSyePCq4kU2wMdb2fBfb9P9Q== dependencies: eslint "~6.8.0" eslint-config-standard "14.1.1" eslint-config-standard-jsx "8.1.0" eslint-plugin-import "~2.18.0" eslint-plugin-node "~10.0.0" eslint-plugin-promise "~4.2.1" eslint-plugin-react "~7.14.2" eslint-plugin-standard "~4.0.0" standard-engine "^12.0.0" [email protected]: version "2.0.1" resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63" integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ== stream-chain@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/stream-chain/-/stream-chain-2.2.3.tgz#44cfa21ab673e53a3f1691b3d1665c3aceb1983b" integrity sha512-w+WgmCZ6BItPAD3/4HD1eDiDHRLhjSSyIV+F0kcmmRyz8Uv9hvQF22KyaiAUmOlmX3pJ6F95h+C191UbS8Oe/g== stream-json@^1.7.1: version "1.7.1" resolved "https://registry.yarnpkg.com/stream-json/-/stream-json-1.7.1.tgz#ec7e414c2eba456c89a4b4e5223794eabc3860c4" integrity sha512-I7g0IDqvdJXbJ279/D3ZoTx0VMhmKnEF7u38CffeWdF8bfpMPsLo+5fWnkNjO2GU/JjWaRjdH+zmH03q+XGXFw== dependencies: stream-chain "^2.2.3" [email protected]: version "0.3.1" resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== string-width@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-3.1.0.tgz#22767be21b62af1081574306f69ac51b62203961" integrity sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w== dependencies: emoji-regex "^7.0.1" is-fullwidth-code-point "^2.0.0" strip-ansi "^5.1.0" string-width@^4.1.0, string-width@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.0.tgz#952182c46cc7b2c313d1596e623992bd163b72b5" integrity sha512-zUz5JD+tgqtuDjMhwIg5uFVV3dtqZ9yQJlZVfq4I01/K5Paj5UHj7VyrQOJvzawSVlKpObApbfD0Ed6yJc+1eg== dependencies: emoji-regex "^8.0.0" is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" string-width@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.0.0.tgz#19191f152f937b96f4ec54ba0986a5656660c5a2" integrity sha512-zwXcRmLUdiWhMPrHz6EXITuyTgcEnUqDzspTkCLhQovxywWz6NP9VHgqfVg20V/1mUg0B95AKbXxNT+ALRmqCw== dependencies: emoji-regex "^9.2.2" is-fullwidth-code-point "^4.0.0" strip-ansi "^7.0.0" string.prototype.trimend@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz#85812a6b847ac002270f5808146064c995fb6913" integrity sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string.prototype.trimstart@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz#14af6d9f34b053f7cfc89b72f8f2ee14b9039a54" integrity sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw== dependencies: define-properties "^1.1.3" es-abstract "^1.17.5" string_decoder@^1.1.1: version "1.3.0" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== dependencies: safe-buffer "~5.2.0" string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" stringify-object@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== dependencies: get-own-enumerable-property-symbols "^3.0.0" is-obj "^1.0.1" is-regexp "^1.0.0" strip-ansi@^5.1.0, strip-ansi@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-5.2.0.tgz#8c9a536feb6afc962bdfa5b104a5091c1ad9c0ae" integrity sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA== dependencies: ansi-regex "^4.1.0" strip-ansi@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" integrity sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w== dependencies: ansi-regex "^5.0.0" strip-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.0.tgz#1dc49b980c3a4100366617adac59327eefdefcb0" integrity sha512-UhDTSnGF1dc0DRbUqr1aXwNoY3RgVkSWG8BrpnuFIxhP57IqbS7IRta2Gfiavds4yCxc5+fEAVVOgBZWnYkvzg== dependencies: ansi-regex "^6.0.0" strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= strip-final-newline@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== strip-json-comments@^3.0.1, strip-json-comments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.0.tgz#7638d31422129ecf4457440009fba03f9f9ac180" integrity sha512-e6/d0eBu7gHtdCqFt0xJr642LdToM5/cN4Qb9DbHjVx1CP5RyeM+zH7pbecEmDv/lBqb0QH+6Uqq75rxFPkM0w== strip-json-comments@~3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== sumchecker@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/sumchecker/-/sumchecker-3.0.1.tgz#6377e996795abb0b6d348e9b3e1dfb24345a8e42" integrity sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg== dependencies: debug "^4.1.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" supports-color@^7.1.0: version "7.1.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.1.0.tgz#68e32591df73e25ad1c4b49108a2ec507962bfd1" integrity sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g== dependencies: has-flag "^4.0.0" supports-color@^8.0.0: version "8.1.1" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== dependencies: has-flag "^4.0.0" supports-color@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.0.2.tgz#50f082888e4b0a4e2ccd2d0b4f9ef4efcd332485" integrity sha512-ii6tc8ImGFrgMPYq7RVAMKkhPo9vk8uA+D3oKbJq/3Pk2YSMv1+9dUAesa9UxMbxBTvxwKTQffBahNVNxEvM8Q== dependencies: has-flag "^5.0.0" supports-preserve-symlinks-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== table@^5.2.3: version "5.4.6" resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e" integrity sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug== dependencies: ajv "^6.10.2" lodash "^4.17.14" slice-ansi "^2.1.0" string-width "^3.0.0" tap-parser@~1.2.2: version "1.2.2" resolved "https://registry.yarnpkg.com/tap-parser/-/tap-parser-1.2.2.tgz#5e2f6970611f079c7cf857de1dc7aa1b480de7a5" integrity sha1-Xi9pcGEfB5x8+FfeHceqG0gN56U= dependencies: events-to-array "^1.0.1" inherits "~2.0.1" js-yaml "^3.2.7" optionalDependencies: readable-stream "^2" tap-xunit@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/tap-xunit/-/tap-xunit-2.4.1.tgz#9823797b676ae5017f4e380bd70abb893b8e120e" integrity sha512-qcZStDtjjYjMKAo7QNiCtOW256g3tuSyCSe5kNJniG1Q2oeOExJq4vm8CwboHZURpkXAHvtqMl4TVL7mcbMVVA== dependencies: duplexer "~0.1.1" minimist "~1.2.0" tap-parser "~1.2.2" through2 "~2.0.0" xmlbuilder "~4.2.0" xtend "~4.0.0" tapable@^1.0.0: version "1.1.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA== tapable@^2.1.1, tapable@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== tar@^6.1.11: version "6.1.13" resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b" integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw== dependencies: chownr "^2.0.0" fs-minipass "^2.0.0" minipass "^4.0.0" minizlib "^2.1.1" mkdirp "^1.0.3" yallist "^4.0.0" temp@^0.8.3: version "0.8.3" resolved "https://registry.yarnpkg.com/temp/-/temp-0.8.3.tgz#e0c6bc4d26b903124410e4fed81103014dfc1f59" integrity sha1-4Ma8TSa5AxJEEOT+2BEDAU38H1k= dependencies: os-tmpdir "^1.0.0" rimraf "~2.2.6" terser-webpack-plugin@^5.1.3: version "5.3.3" resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.3.tgz#8033db876dd5875487213e87c627bca323e5ed90" integrity sha512-Fx60G5HNYknNTNQnzQ1VePRuu89ZVYWfjRAeT5rITuCY/1b08s49e5kSQwHDirKZWuoKOBRFS98EUUoZ9kLEwQ== dependencies: "@jridgewell/trace-mapping" "^0.3.7" jest-worker "^27.4.5" schema-utils "^3.1.1" serialize-javascript "^6.0.0" terser "^5.7.2" terser@^5.7.2: version "5.14.2" resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== dependencies: "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" commander "^2.20.0" source-map-support "~0.5.20" text-table@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= through2@~2.0.0: version "2.0.5" resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== dependencies: readable-stream "~2.3.6" xtend "~4.0.1" through@^2.3.6, through@^2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= [email protected]: version "1.4.2" resolved "https://registry.yarnpkg.com/timers-browserify/-/timers-browserify-1.4.2.tgz#c9c58b575be8407375cb5e2462dacee74359f41d" integrity sha1-ycWLV1voQHN1y14kYtrO50NZ9B0= dependencies: process "~0.11.0" tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== dependencies: os-tmpdir "~1.0.2" to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== dependencies: is-number "^7.0.0" to-vfile@^7.0.0: version "7.2.1" resolved "https://registry.yarnpkg.com/to-vfile/-/to-vfile-7.2.1.tgz#fe42892024f724177ba81076f98ee74b0888c293" integrity sha512-biljADNq2n+AZn/zX+/87zStnIqctKr/q5OaOD8+qSKINokUGPbWBShvxa1iLUgHz6dGGjVnQPNoFRtVBzMkVg== dependencies: is-buffer "^2.0.0" vfile "^5.0.0" [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== tough-cookie@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.0.0.tgz#d822234eeca882f991f0f908824ad2622ddbece4" integrity sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg== dependencies: psl "^1.1.33" punycode "^2.1.1" universalify "^0.1.2" tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o= trough@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/trough/-/trough-2.0.2.tgz#94a3aa9d5ce379fc561f6244905b3f36b7458d96" integrity sha512-FnHq5sTMxC0sk957wHDzRnemFnNBvt/gSY99HzK8F7UP5WAbvP70yX5bd7CjEQkN+TjdxwI7g7lJ6podqrG2/w== ts-loader@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-8.0.2.tgz#ee73ca9350f745799396fff8578ba29b1e95616b" integrity sha512-oYT7wOTUawYXQ8XIDsRhziyW0KUEV38jISYlE+9adP6tDtG+O5GkRe4QKQXrHVH4mJJ88DysvEtvGP65wMLlhg== dependencies: chalk "^2.3.0" enhanced-resolve "^4.0.0" loader-utils "^1.0.2" micromatch "^4.0.0" semver "^6.0.0" [email protected]: version "6.2.0" resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-6.2.0.tgz#65a0ae2acce319ea4fd7ac8d7c9f1f90c5da6baf" integrity sha512-ZNT+OEGfUNVMGkpIaDJJ44Zq3Yr0bkU/ugN1PHbU+/01Z7UV1fsELRiTx1KuQNvQ1A3pGh3y25iYF6jXgxV21A== dependencies: arrify "^1.0.0" buffer-from "^1.1.0" diff "^3.1.0" make-error "^1.1.1" minimist "^1.2.0" mkdirp "^0.5.1" source-map-support "^0.5.6" yn "^2.0.0" tsconfig-paths@^3.9.0: version "3.9.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz#098547a6c4448807e8fcb8eae081064ee9a3c90b" integrity sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw== dependencies: "@types/json5" "^0.0.29" json5 "^1.0.1" minimist "^1.2.0" strip-bom "^3.0.0" tslib@^1.8.1, tslib@^1.9.0: version "1.10.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== tslib@^2.0.0, tslib@^2.2.0: version "2.3.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== dependencies: tslib "^1.8.1" tunnel@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== dependencies: prelude-ls "^1.2.1" type-check@~0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" integrity sha1-WITKtRLPHTVeP7eE8wgEsrUg23I= dependencies: prelude-ls "~1.1.2" type-detect@^4.0.0, type-detect@^4.0.5: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== type-fest@^0.11.0: version "0.11.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.11.0.tgz#97abf0872310fed88a5c466b25681576145e33f1" integrity sha512-OdjXJxnCN1AvyLSzeKIgXTXxV+99ZuXl3Hpo9XpJAv9MBcHrrJOQ5kV7ypXOuQie+AmWG25hLbiKdwYTifzcfQ== type-fest@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934" integrity sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg== type-fest@^0.3.0: version "0.3.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" integrity sha512-cUGJnCdr4STbePCgqNFbpVNCepa+kAVohJs1sLhxzdH+gnEoOd8VhbYa7pD3zZYGiURWM2xzEII3fQcRizDkYQ== type-fest@^0.8.1: version "0.8.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== type-is@~1.6.18: version "1.6.18" resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131" integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g== dependencies: media-typer "0.3.0" mime-types "~2.1.24" typedarray@^0.0.6: version "0.0.6" resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= typescript@^4.5.5: version "4.5.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.5.tgz#d8c953832d28924a9e3d37c73d729c846c5896f3" integrity sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA== uc.micro@^1.0.1, uc.micro@^1.0.5: version "1.0.6" resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== unified-args@^9.0.0: version "9.0.2" resolved "https://registry.yarnpkg.com/unified-args/-/unified-args-9.0.2.tgz#0c14f555e73ee29c23f9a567942e29069f56e5a2" integrity sha512-qSqryjoqfJSII4E4Z2Jx7MhXX2MuUIn6DsrlmL8UnWFdGtrWvEtvm7Rx5fKT5TPUz7q/Fb4oxwIHLCttvAuRLQ== dependencies: "@types/text-table" "^0.2.0" camelcase "^6.0.0" chalk "^4.0.0" chokidar "^3.0.0" fault "^2.0.0" json5 "^2.0.0" minimist "^1.0.0" text-table "^0.2.0" unified-engine "^9.0.0" unified-engine@^9.0.0: version "9.0.3" resolved "https://registry.yarnpkg.com/unified-engine/-/unified-engine-9.0.3.tgz#c1d57e67d94f234296cbfa9364f43e0696dae016" integrity sha512-SgzREcCM2IpUy3JMFUcPRZQ2Py6IwvJ2KIrg2AiI7LnGge6E6OPFWpcabHrEXG0IvO2OI3afiD9DOcQvvZfXDQ== dependencies: "@types/concat-stream" "^1.0.0" "@types/debug" "^4.0.0" "@types/is-empty" "^1.0.0" "@types/js-yaml" "^4.0.0" "@types/node" "^16.0.0" "@types/unist" "^2.0.0" concat-stream "^2.0.0" debug "^4.0.0" fault "^2.0.0" glob "^7.0.0" ignore "^5.0.0" is-buffer "^2.0.0" is-empty "^1.0.0" is-plain-obj "^4.0.0" js-yaml "^4.0.0" load-plugin "^4.0.0" parse-json "^5.0.0" to-vfile "^7.0.0" trough "^2.0.0" unist-util-inspect "^7.0.0" vfile-message "^3.0.0" vfile-reporter "^7.0.0" vfile-statistics "^2.0.0" unified-lint-rule@^1.0.0: version "1.0.4" resolved "https://registry.yarnpkg.com/unified-lint-rule/-/unified-lint-rule-1.0.4.tgz#be432d316db7ad801166041727b023ba18963e24" integrity sha512-q9wY6S+d38xRAuWQVOMjBQYi7zGyKkY23ciNafB8JFVmDroyKjtytXHCg94JnhBCXrNqpfojo3+8D+gmF4zxJQ== dependencies: wrapped "^1.0.1" unified-message-control@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unified-message-control/-/unified-message-control-3.0.3.tgz#d08c4564092a507668de71451a33c0d80e734bbd" integrity sha512-oY5z2n8ugjpNHXOmcgrw0pQeJzavHS0VjPBP21tOcm7rc2C+5Q+kW9j5+gqtf8vfW/8sabbsK5+P+9QPwwEHDA== dependencies: unist-util-visit "^2.0.0" vfile-location "^3.0.0" unified@^10.0.0: version "10.1.0" resolved "https://registry.yarnpkg.com/unified/-/unified-10.1.0.tgz#4e65eb38fc2448b1c5ee573a472340f52b9346fe" integrity sha512-4U3ru/BRXYYhKbwXV6lU6bufLikoAavTwev89H5UxY8enDFaAT2VXmIXYNm6hb5oHPng/EXr77PVyDFcptbk5g== dependencies: "@types/unist" "^2.0.0" bail "^2.0.0" extend "^3.0.0" is-buffer "^2.0.0" is-plain-obj "^4.0.0" trough "^2.0.0" vfile "^5.0.0" uniq@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/uniq/-/uniq-1.0.1.tgz#b31c5ae8254844a3a8281541ce2b04b865a734ff" integrity sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8= unist-util-generated@^1.0.0: version "1.1.6" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.6.tgz#5ab51f689e2992a472beb1b35f2ce7ff2f324d4b" integrity sha512-cln2Mm1/CZzN5ttGK7vkoGw+RZ8VcUH6BtGbq98DDtRGquAAOXig1mrBQYelOwMXYS8rK+vZDyyojSjp7JX+Lg== unist-util-generated@^1.1.0: version "1.1.4" resolved "https://registry.yarnpkg.com/unist-util-generated/-/unist-util-generated-1.1.4.tgz#2261c033d9fc23fae41872cdb7663746e972c1a7" integrity sha512-SA7Sys3h3X4AlVnxHdvN/qYdr4R38HzihoEVY2Q2BZu8NHWDnw5OGcC/tXWjQfd4iG+M6qRFNIRGqJmp2ez4Ww== unist-util-inspect@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/unist-util-inspect/-/unist-util-inspect-7.0.0.tgz#98426f0219e24d011a27e32539be0693d9eb973e" integrity sha512-2Utgv78I7PUu461Y9cdo+IUiiKSKpDV5CE/XD6vTj849a3xlpDAScvSJ6cQmtFBGgAmCn2wR7jLuXhpg1XLlJw== dependencies: "@types/unist" "^2.0.0" unist-util-is@^4.0.0: version "4.1.0" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-4.1.0.tgz#976e5f462a7a5de73d94b706bac1b90671b57797" integrity sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg== unist-util-is@^5.0.0: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-is/-/unist-util-is-5.1.1.tgz#e8aece0b102fa9bc097b0fef8f870c496d4a6236" integrity sha512-F5CZ68eYzuSvJjGhCLPL3cYx45IxkqXSetCcRgUXtbcm50X2L9oOWQlfUfDdAf+6Pd27YDblBfdtmsThXmwpbQ== unist-util-position@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/unist-util-position/-/unist-util-position-3.0.3.tgz#fff942b879538b242096c148153826664b1ca373" integrity sha512-28EpCBYFvnMeq9y/4w6pbnFmCUfzlsc41NJui5c51hOFjBA1fejcwc+5W4z2+0ECVbScG3dURS3JTVqwenzqZw== unist-util-stringify-position@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-2.0.1.tgz#de2a2bc8d3febfa606652673a91455b6a36fb9f3" integrity sha512-Zqlf6+FRI39Bah8Q6ZnNGrEHUhwJOkHde2MHVk96lLyftfJJckaPslKgzhVcviXj8KcE9UJM9F+a4JEiBUTYgA== dependencies: "@types/unist" "^2.0.2" unist-util-stringify-position@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-3.0.0.tgz#d517d2883d74d0daa0b565adc3d10a02b4a8cde9" integrity sha512-SdfAl8fsDclywZpfMDTVDxA2V7LjtRDTOFd44wUJamgl6OlVngsqWjxvermMYf60elWHbxhuRCZml7AnuXCaSA== dependencies: "@types/unist" "^2.0.0" unist-util-visit-parents@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz#65a6ce698f78a6b0f56aa0e88f13801886cdaef6" integrity sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-5.1.1.tgz#868f353e6fce6bf8fa875b251b0f4fec3be709bb" integrity sha512-gks4baapT/kNRaWxuGkl5BIhoanZo7sC/cUT/JToSRNL1dYoXRFl75d++NkjYk4TAu2uv2Px+l8guMajogeuiw== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-2.0.3.tgz#c3703893146df47203bb8a9795af47d7b971208c" integrity sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q== dependencies: "@types/unist" "^2.0.0" unist-util-is "^4.0.0" unist-util-visit-parents "^3.0.0" unist-util-visit@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.1.tgz#1c4842d70bd3df6cc545276f5164f933390a9aad" integrity sha512-n9KN3WV9k4h1DxYR1LoajgN93wpEi/7ZplVe02IoB4gH5ctI1AaF2670BLHQYbwj+pY83gFtyeySFiyMHJklrg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" unist-util-visit-parents "^5.1.1" universal-github-app-jwt@^1.0.1: version "1.1.1" resolved "https://registry.yarnpkg.com/universal-github-app-jwt/-/universal-github-app-jwt-1.1.1.tgz#d57cee49020662a95ca750a057e758a1a7190e6e" integrity sha512-G33RTLrIBMFmlDV4u4CBF7dh71eWwykck4XgaxaIVeZKOYZRAAxvcGMRFTUclVY6xoUPQvO4Ne5wKGxYm/Yy9w== dependencies: "@types/jsonwebtoken" "^9.0.0" jsonwebtoken "^9.0.0" universal-user-agent@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== universalify@^0.1.0, universalify@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== universalify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d" integrity sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug== universalify@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== [email protected], unpipe@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" integrity sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw= update-browserslist-db@^1.0.4: version "1.0.5" resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38" integrity sha512-dteFFpCyvuDdr9S/ff1ISkKt/9YZxKjI9WlRR99c180GaztJtRa/fn18FdxGVKVsnPY7/a/FDN68mcvUmP4U7Q== dependencies: escalade "^3.1.1" picocolors "^1.0.0" uri-js@^4.2.2: version "4.4.1" resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== dependencies: punycode "^2.1.0" [email protected]: version "0.10.3" resolved "https://registry.yarnpkg.com/url/-/url-0.10.3.tgz#021e4d9c7705f21bbf37d03ceb58767402774c64" integrity sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ= dependencies: punycode "1.3.2" querystring "0.2.0" util-deprecate@^1.0.1, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= [email protected]: version "1.0.1" resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM= [email protected]: version "3.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131" integrity sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA== uuid@^8.3.0: version "8.3.2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== uvu@^0.5.0: version "0.5.6" resolved "https://registry.yarnpkg.com/uvu/-/uvu-0.5.6.tgz#2754ca20bcb0bb59b64e9985e84d2e81058502df" integrity sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA== dependencies: dequal "^2.0.0" diff "^5.0.0" kleur "^4.0.3" sade "^1.7.3" v8-compile-cache@^2.0.3: version "2.1.1" resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.1.1.tgz#54bc3cdd43317bca91e35dcaf305b1a7237de745" integrity sha512-8OQ9CL+VWyt3JStj7HX7/ciTL2V3Rl1Wf5OL+SNTm0yK1KvtReVulksyeRnCANHHuUxHlQig+JJDlUhBt1NQDQ== validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" vary@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc" integrity sha1-IpnwLG3tMNSllhsLn3RSShj2NPw= vfile-location@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-3.2.0.tgz#d8e41fbcbd406063669ebf6c33d56ae8721d0f3c" integrity sha512-aLEIZKv/oxuCDZ8lkJGhuhztf/BW4M+iHdCwglA/eWc+vtuRFJj8EtgceYFX4LRjOhCAAiNHsKGssC6onJ+jbA== vfile-message@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.0.1.tgz#b9bcf87cb5525e61777e0c6df07e816a577588a3" integrity sha512-gYmSHcZZUEtYpTmaWaFJwsuUD70/rTY4v09COp8TGtOkix6gGxb/a8iTQByIY9ciTk9GwAwIXd/J9OPfM4Bvaw== dependencies: "@types/unist" "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-reporter@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.1.tgz#759bfebb995f3dc8c644284cb88ac4b310ebd168" integrity sha512-pof+cQSJCUNmHG6zoBOJfErb6syIWHWM14CwKjsugCixxl4CZdrgzgxwLBW8lIB6czkzX0Agnnhj33YpKyLvmA== dependencies: "@types/repeat-string" "^1.0.0" "@types/supports-color" "^8.0.0" repeat-string "^1.0.0" string-width "^5.0.0" supports-color "^9.0.0" unist-util-stringify-position "^3.0.0" vfile-sort "^3.0.0" vfile-statistics "^2.0.0" vfile-sort@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/vfile-sort/-/vfile-sort-3.0.0.tgz#ee13d3eaac0446200a2047a3b45d78fad6b106e6" integrity sha512-fJNctnuMi3l4ikTVcKpxTbzHeCgvDhnI44amA3NVDvA6rTC6oKCFpCVyT5n2fFMr3ebfr+WVQZedOCd73rzSxg== dependencies: vfile-message "^3.0.0" vfile-statistics@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/vfile-statistics/-/vfile-statistics-2.0.0.tgz#f04ee3e3c666809a3c10c06021becd41ea9c8037" integrity sha512-foOWtcnJhKN9M2+20AOTlWi2dxNfAoeNIoxD5GXcO182UJyId4QrXa41fWrgcfV3FWTjdEDy3I4cpLVcQscIMA== dependencies: vfile-message "^3.0.0" vfile@^5.0.0: version "5.0.2" resolved "https://registry.yarnpkg.com/vfile/-/vfile-5.0.2.tgz#57773d1d91478b027632c23afab58ec3590344f0" integrity sha512-5cV+K7tX83MT3bievROc+7AvHv0GXDB0zqbrTjbOe+HRbkzvY4EP+wS3IR77kUBCoWFMdG9py18t0sesPtQ1Rw== dependencies: "@types/unist" "^2.0.0" is-buffer "^2.0.0" unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" [email protected]: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz#f239ed2cd6004021b6550af9fd9d3e47eee3cac9" integrity sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ== [email protected]: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz#beaa46aea06ed061576586c5e11368a9afc1d378" integrity sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg== dependencies: vscode-jsonrpc "8.0.2" vscode-languageserver-types "3.17.2" vscode-languageserver-textdocument@^1.0.5, vscode-languageserver-textdocument@^1.0.7: version "1.0.7" resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz#16df468d5c2606103c90554ae05f9f3d335b771b" integrity sha512-bFJH7UQxlXT8kKeyiyu41r22jCZXG8kuuVVA33OEJn1diWOZK5n8zBSPZFHVBOu8kXZ6h0LIRhf5UnCo61J4Hg== [email protected], vscode-languageserver-types@^3.17.1: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz#b2c2e7de405ad3d73a883e91989b850170ffc4f2" integrity sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA== vscode-languageserver@^8.0.2: version "8.0.2" resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.0.2.tgz#cfe2f0996d9dfd40d3854e786b2821604dfec06d" integrity sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA== dependencies: vscode-languageserver-protocol "3.17.2" vscode-uri@^3.0.3, vscode-uri@^3.0.6: version "3.0.6" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.6.tgz#5e6e2e1a4170543af30151b561a41f71db1d6f91" integrity sha512-fmL7V1eiDBFRRnu+gfRWTzyPpNIHJTc4mWnFkwBUmO9U3KPgJAmTx7oxi2bl/Rh6HLdU7+4C9wlj0k2E4AdKFQ== walk-sync@^0.3.2: version "0.3.4" resolved "https://registry.yarnpkg.com/walk-sync/-/walk-sync-0.3.4.tgz#cf78486cc567d3a96b5b2237c6108017a5ffb9a4" integrity sha512-ttGcuHA/OBnN2pcM6johpYlEms7XpO5/fyKIr48541xXedan4roO8cS1Q2S/zbbjGH/BarYDAMeS2Mi9HE5Tig== dependencies: ensure-posix-path "^1.0.0" matcher-collection "^1.0.0" watchpack@^2.3.1: version "2.4.0" resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== dependencies: glob-to-regexp "^0.4.1" graceful-fs "^4.1.2" wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" integrity sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g= dependencies: defaults "^1.0.3" webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE= webpack-cli@^4.10.0: version "4.10.0" resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== dependencies: "@discoveryjs/json-ext" "^0.5.0" "@webpack-cli/configtest" "^1.2.0" "@webpack-cli/info" "^1.5.0" "@webpack-cli/serve" "^1.7.0" colorette "^2.0.14" commander "^7.0.0" cross-spawn "^7.0.3" fastest-levenshtein "^1.0.12" import-local "^3.0.2" interpret "^2.2.0" rechoir "^0.7.0" webpack-merge "^5.7.3" webpack-merge@^5.7.3: version "5.8.0" resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" integrity sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q== dependencies: clone-deep "^4.0.1" wildcard "^2.0.0" webpack-sources@^3.2.3: version "3.2.3" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== webpack@^5, webpack@^5.73.0: version "5.73.0" resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.73.0.tgz#bbd17738f8a53ee5760ea2f59dce7f3431d35d38" integrity sha512-svjudQRPPa0YiOYa2lM/Gacw0r6PvxptHj4FuEKQ2kX05ZLkjbVc5MnPs6its5j7IZljnIqSVo/OsY2X0IpHGA== dependencies: "@types/eslint-scope" "^3.7.3" "@types/estree" "^0.0.51" "@webassemblyjs/ast" "1.11.1" "@webassemblyjs/wasm-edit" "1.11.1" "@webassemblyjs/wasm-parser" "1.11.1" acorn "^8.4.1" acorn-import-assertions "^1.7.6" browserslist "^4.14.5" chrome-trace-event "^1.0.2" enhanced-resolve "^5.9.3" es-module-lexer "^0.9.0" eslint-scope "5.1.1" events "^3.2.0" glob-to-regexp "^0.4.1" graceful-fs "^4.2.9" json-parse-even-better-errors "^2.3.1" loader-runner "^4.2.0" mime-types "^2.1.27" neo-async "^2.6.2" schema-utils "^3.1.0" tapable "^2.1.1" terser-webpack-plugin "^5.1.3" watchpack "^2.3.1" webpack-sources "^3.2.3" whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" integrity sha1-lmRU6HZUYuN2RNNib2dCzotwll0= dependencies: tr46 "~0.0.3" webidl-conversions "^3.0.0" which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== dependencies: isexe "^2.0.0" which@^2.0.1: version "2.0.2" resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== dependencies: isexe "^2.0.0" wildcard@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== word-wrap@^1.2.3, word-wrap@~1.2.3: version "1.2.3" resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== wrap-ansi@^6.2.0: version "6.2.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== dependencies: ansi-styles "^4.0.0" string-width "^4.1.0" strip-ansi "^6.0.0" wrapped@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wrapped/-/wrapped-1.0.1.tgz#c783d9d807b273e9b01e851680a938c87c907242" integrity sha1-x4PZ2Aeyc+mwHoUWgKk4yHyQckI= dependencies: co "3.1.0" sliced "^1.0.1" wrapper-webpack-plugin@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/wrapper-webpack-plugin/-/wrapper-webpack-plugin-2.2.2.tgz#a950b7fbc39ca103e468a7c06c225cb1e337ad3b" integrity sha512-twLGZw0b2AEnz3LmsM/uCFRzGxE+XUlUPlJkCuHY3sI+uGO4dTJsgYee3ufWJaynAZYkpgQSKMSr49n9Yxalzg== wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= [email protected]: version "1.0.3" resolved "https://registry.yarnpkg.com/write/-/write-1.0.3.tgz#0800e14523b923a387e415123c865616aae0f5c3" integrity sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig== dependencies: mkdirp "^0.5.1" [email protected]: version "0.4.19" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.19.tgz#686c20f213209e94abf0d1bcf1efaa291c7827a7" integrity sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q== dependencies: sax ">=0.6.0" xmlbuilder "~9.0.1" xml2js@^0.4.19: version "0.4.23" resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.23.tgz#a0c69516752421eb2ac758ee4d4ccf58843eac66" integrity sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug== dependencies: sax ">=0.6.0" xmlbuilder "~11.0.0" xmlbuilder@~11.0.0: version "11.0.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3" integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA== xmlbuilder@~4.2.0: version "4.2.1" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5" integrity sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU= dependencies: lodash "^4.0.0" xmlbuilder@~9.0.1: version "9.0.7" resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-9.0.7.tgz#132ee63d2ec5565c557e20f4c22df9aca686b10d" integrity sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0= xtend@^4.0.1, xtend@~4.0.0, xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== yallist@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== yaml@^1.7.2: version "1.10.0" resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9" integrity sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g== dependencies: buffer-crc32 "~0.2.3" fd-slicer "~1.1.0" yn@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/yn/-/yn-2.0.0.tgz#e5adabc8acf408f6385fc76495684c88e6af689a" integrity sha1-5a2ryKz0CPY4X8dklWhMiOavaJo= zwitch@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-2.0.2.tgz#91f8d0e901ffa3d66599756dde7f57b17c95dce1" integrity sha512-JZxotl7SxAJH0j7dN4pxsTV6ZLXoLdGME+PsjkL/DaBrVryK9kTGq06GfKrwcSOqypP+fdXGoCHE36b99fWVoA==
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### 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 title='main.js' 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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 title='main.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. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Web Bluetooth API</title> </head> <body> <h1>Web Bluetooth API</h1> <button id="clickme">Test Bluetooth</button> <p>Currently selected bluetooth device: <strong id="device-name""></strong></p> <script src="./renderer.js"></script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/main.js
const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() if (deviceList && deviceList.length > 0) { callback(deviceList[0].deviceId) } }) // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow.webContents.send('bluetooth-pairing-request', details) }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/preload.js
const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/renderer.js
async function testIt() { const device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true }) document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}` } document.getElementById('clickme').addEventListener('click',testIt) window.electronAPI.bluetoothPairingRequest((event, details) => { const response = {} switch (details.pairingKind) { case 'confirm': { response.confirmed = confirm(`Do you want to connect to device ${details.deviceId}?`) break } case 'confirmPin': { response.confirmed = confirm(`Does the pin ${details.pin} match the pin displayed on device ${details.deviceId}?`) break } case 'providePin': { const pin = prompt(`Please provide a pin for ${details.deviceId}.`) if (pin) { response.pin = pin response.confirmed = true } else { response.confirmed = false } } } window.electronAPI.bluetoothPairingResponse(response) })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/lib/bluetooth_chooser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" namespace gin { template <> struct Converter<electron::BluetoothChooser::DeviceInfo> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::BluetoothChooser::DeviceInfo& val) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("deviceName", val.device_name); dict.Set("deviceId", val.device_id); return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace { const int kMaxScanRetries = 5; void OnDeviceChosen(const content::BluetoothChooser::EventHandler& handler, const std::string& device_id) { if (device_id.empty()) { handler.Run(content::BluetoothChooserEvent::CANCELLED, device_id); } else { handler.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } // namespace BluetoothChooser::BluetoothChooser(api::WebContents* contents, const EventHandler& event_handler) : api_web_contents_(contents), event_handler_(event_handler) {} BluetoothChooser::~BluetoothChooser() { event_handler_.Reset(); } void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { switch (presence) { case AdapterPresence::ABSENT: case AdapterPresence::POWERED_OFF: // Chrome currently directs the user to system preferences // to grant bluetooth permission for this case, should we // do something similar ? // https://chromium-review.googlesource.com/c/chromium/src/+/2617129 case AdapterPresence::UNAUTHORIZED: event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case AdapterPresence::POWERED_ON: rescan_ = true; break; } } void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { switch (state) { case DiscoveryState::FAILED_TO_START: refreshing_ = false; event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case DiscoveryState::IDLE: refreshing_ = false; if (device_map_.empty()) { auto event = ++num_retries_ > kMaxScanRetries ? content::BluetoothChooserEvent::CANCELLED : content::BluetoothChooserEvent::RESCAN; event_handler_.Run(event, ""); } else { bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); if (!prevent_default) { auto it = device_map_.begin(); auto device_id = it->first; event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } break; case DiscoveryState::DISCOVERING: // The first time this state fires is due to a rescan triggering so set a // flag to ignore devices if (rescan_ && !refreshing_) { refreshing_ = true; } else { // The second time this state fires we are now safe to pick a device refreshing_ = false; } break; } } void BluetoothChooser::AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) { if (refreshing_) { // If the list of bluetooth devices is currently being generated don't fire // an event return; } bool changed = false; auto entry = device_map_.find(device_id); if (entry == device_map_.end()) { device_map_[device_id] = device_name; changed = true; } else if (should_update_name) { entry->second = device_name; changed = true; } if (changed) { // Emit a select-bluetooth-device handler to allow for user to listen for // bluetooth device found. bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); // If emit not implemented select first device that matches the filters // provided. if (!prevent_default) { event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } std::vector<electron::BluetoothChooser::DeviceInfo> BluetoothChooser::GetDeviceList() { std::vector<electron::BluetoothChooser::DeviceInfo> vec; vec.reserve(device_map_.size()); for (const auto& it : device_map_) { DeviceInfo info = {it.first, it.second}; vec.push_back(info); } return vec; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.h
// Copyright (c) 2016 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_LIB_BLUETOOTH_CHOOSER_H_ #define ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ #include <map> #include <string> #include <vector> #include "content/public/browser/bluetooth_chooser.h" #include "shell/browser/api/electron_api_web_contents.h" namespace electron { class BluetoothChooser : public content::BluetoothChooser { public: struct DeviceInfo { std::string device_id; std::u16string device_name; }; explicit BluetoothChooser(api::WebContents* contents, const EventHandler& handler); ~BluetoothChooser() override; // disable copy BluetoothChooser(const BluetoothChooser&) = delete; BluetoothChooser& operator=(const BluetoothChooser&) = delete; // content::BluetoothChooser: void SetAdapterPresence(AdapterPresence presence) override; void ShowDiscoveryState(DiscoveryState state) override; void AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) override; std::vector<DeviceInfo> GetDeviceList(); private: std::map<std::string, std::u16string> device_map_; api::WebContents* api_web_contents_; EventHandler event_handler_; int num_retries_ = 0; bool refreshing_ = false; bool rescan_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### 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 title='main.js' 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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 title='main.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. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Web Bluetooth API</title> </head> <body> <h1>Web Bluetooth API</h1> <button id="clickme">Test Bluetooth</button> <p>Currently selected bluetooth device: <strong id="device-name""></strong></p> <script src="./renderer.js"></script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/main.js
const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() if (deviceList && deviceList.length > 0) { callback(deviceList[0].deviceId) } }) // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow.webContents.send('bluetooth-pairing-request', details) }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/preload.js
const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/renderer.js
async function testIt() { const device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true }) document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}` } document.getElementById('clickme').addEventListener('click',testIt) window.electronAPI.bluetoothPairingRequest((event, details) => { const response = {} switch (details.pairingKind) { case 'confirm': { response.confirmed = confirm(`Do you want to connect to device ${details.deviceId}?`) break } case 'confirmPin': { response.confirmed = confirm(`Does the pin ${details.pin} match the pin displayed on device ${details.deviceId}?`) break } case 'providePin': { const pin = prompt(`Please provide a pin for ${details.deviceId}.`) if (pin) { response.pin = pin response.confirmed = true } else { response.confirmed = false } } } window.electronAPI.bluetoothPairingResponse(response) })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/lib/bluetooth_chooser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" namespace gin { template <> struct Converter<electron::BluetoothChooser::DeviceInfo> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::BluetoothChooser::DeviceInfo& val) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("deviceName", val.device_name); dict.Set("deviceId", val.device_id); return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace { const int kMaxScanRetries = 5; void OnDeviceChosen(const content::BluetoothChooser::EventHandler& handler, const std::string& device_id) { if (device_id.empty()) { handler.Run(content::BluetoothChooserEvent::CANCELLED, device_id); } else { handler.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } // namespace BluetoothChooser::BluetoothChooser(api::WebContents* contents, const EventHandler& event_handler) : api_web_contents_(contents), event_handler_(event_handler) {} BluetoothChooser::~BluetoothChooser() { event_handler_.Reset(); } void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { switch (presence) { case AdapterPresence::ABSENT: case AdapterPresence::POWERED_OFF: // Chrome currently directs the user to system preferences // to grant bluetooth permission for this case, should we // do something similar ? // https://chromium-review.googlesource.com/c/chromium/src/+/2617129 case AdapterPresence::UNAUTHORIZED: event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case AdapterPresence::POWERED_ON: rescan_ = true; break; } } void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { switch (state) { case DiscoveryState::FAILED_TO_START: refreshing_ = false; event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case DiscoveryState::IDLE: refreshing_ = false; if (device_map_.empty()) { auto event = ++num_retries_ > kMaxScanRetries ? content::BluetoothChooserEvent::CANCELLED : content::BluetoothChooserEvent::RESCAN; event_handler_.Run(event, ""); } else { bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); if (!prevent_default) { auto it = device_map_.begin(); auto device_id = it->first; event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } break; case DiscoveryState::DISCOVERING: // The first time this state fires is due to a rescan triggering so set a // flag to ignore devices if (rescan_ && !refreshing_) { refreshing_ = true; } else { // The second time this state fires we are now safe to pick a device refreshing_ = false; } break; } } void BluetoothChooser::AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) { if (refreshing_) { // If the list of bluetooth devices is currently being generated don't fire // an event return; } bool changed = false; auto entry = device_map_.find(device_id); if (entry == device_map_.end()) { device_map_[device_id] = device_name; changed = true; } else if (should_update_name) { entry->second = device_name; changed = true; } if (changed) { // Emit a select-bluetooth-device handler to allow for user to listen for // bluetooth device found. bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); // If emit not implemented select first device that matches the filters // provided. if (!prevent_default) { event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } std::vector<electron::BluetoothChooser::DeviceInfo> BluetoothChooser::GetDeviceList() { std::vector<electron::BluetoothChooser::DeviceInfo> vec; vec.reserve(device_map_.size()); for (const auto& it : device_map_) { DeviceInfo info = {it.first, it.second}; vec.push_back(info); } return vec; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.h
// Copyright (c) 2016 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_LIB_BLUETOOTH_CHOOSER_H_ #define ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ #include <map> #include <string> #include <vector> #include "content/public/browser/bluetooth_chooser.h" #include "shell/browser/api/electron_api_web_contents.h" namespace electron { class BluetoothChooser : public content::BluetoothChooser { public: struct DeviceInfo { std::string device_id; std::u16string device_name; }; explicit BluetoothChooser(api::WebContents* contents, const EventHandler& handler); ~BluetoothChooser() override; // disable copy BluetoothChooser(const BluetoothChooser&) = delete; BluetoothChooser& operator=(const BluetoothChooser&) = delete; // content::BluetoothChooser: void SetAdapterPresence(AdapterPresence presence) override; void ShowDiscoveryState(DiscoveryState state) override; void AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) override; std::vector<DeviceInfo> GetDeviceList(); private: std::map<std::string, std::u16string> device_map_; api::WebContents* api_web_contents_; EventHandler event_handler_; int num_retries_ = 0; bool refreshing_ = false; bool rescan_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### 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 title='main.js' 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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 title='main.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. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Web Bluetooth API</title> </head> <body> <h1>Web Bluetooth API</h1> <button id="clickme">Test Bluetooth</button> <p>Currently selected bluetooth device: <strong id="device-name""></strong></p> <script src="./renderer.js"></script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/main.js
const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() if (deviceList && deviceList.length > 0) { callback(deviceList[0].deviceId) } }) // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow.webContents.send('bluetooth-pairing-request', details) }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/preload.js
const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/renderer.js
async function testIt() { const device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true }) document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}` } document.getElementById('clickme').addEventListener('click',testIt) window.electronAPI.bluetoothPairingRequest((event, details) => { const response = {} switch (details.pairingKind) { case 'confirm': { response.confirmed = confirm(`Do you want to connect to device ${details.deviceId}?`) break } case 'confirmPin': { response.confirmed = confirm(`Does the pin ${details.pin} match the pin displayed on device ${details.deviceId}?`) break } case 'providePin': { const pin = prompt(`Please provide a pin for ${details.deviceId}.`) if (pin) { response.pin = pin response.confirmed = true } else { response.confirmed = false } } } window.electronAPI.bluetoothPairingResponse(response) })
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/lib/bluetooth_chooser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" namespace gin { template <> struct Converter<electron::BluetoothChooser::DeviceInfo> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::BluetoothChooser::DeviceInfo& val) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("deviceName", val.device_name); dict.Set("deviceId", val.device_id); return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace { const int kMaxScanRetries = 5; void OnDeviceChosen(const content::BluetoothChooser::EventHandler& handler, const std::string& device_id) { if (device_id.empty()) { handler.Run(content::BluetoothChooserEvent::CANCELLED, device_id); } else { handler.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } // namespace BluetoothChooser::BluetoothChooser(api::WebContents* contents, const EventHandler& event_handler) : api_web_contents_(contents), event_handler_(event_handler) {} BluetoothChooser::~BluetoothChooser() { event_handler_.Reset(); } void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { switch (presence) { case AdapterPresence::ABSENT: case AdapterPresence::POWERED_OFF: // Chrome currently directs the user to system preferences // to grant bluetooth permission for this case, should we // do something similar ? // https://chromium-review.googlesource.com/c/chromium/src/+/2617129 case AdapterPresence::UNAUTHORIZED: event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case AdapterPresence::POWERED_ON: rescan_ = true; break; } } void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { switch (state) { case DiscoveryState::FAILED_TO_START: refreshing_ = false; event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case DiscoveryState::IDLE: refreshing_ = false; if (device_map_.empty()) { auto event = ++num_retries_ > kMaxScanRetries ? content::BluetoothChooserEvent::CANCELLED : content::BluetoothChooserEvent::RESCAN; event_handler_.Run(event, ""); } else { bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); if (!prevent_default) { auto it = device_map_.begin(); auto device_id = it->first; event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } break; case DiscoveryState::DISCOVERING: // The first time this state fires is due to a rescan triggering so set a // flag to ignore devices if (rescan_ && !refreshing_) { refreshing_ = true; } else { // The second time this state fires we are now safe to pick a device refreshing_ = false; } break; } } void BluetoothChooser::AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) { if (refreshing_) { // If the list of bluetooth devices is currently being generated don't fire // an event return; } bool changed = false; auto entry = device_map_.find(device_id); if (entry == device_map_.end()) { device_map_[device_id] = device_name; changed = true; } else if (should_update_name) { entry->second = device_name; changed = true; } if (changed) { // Emit a select-bluetooth-device handler to allow for user to listen for // bluetooth device found. bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); // If emit not implemented select first device that matches the filters // provided. if (!prevent_default) { event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } std::vector<electron::BluetoothChooser::DeviceInfo> BluetoothChooser::GetDeviceList() { std::vector<electron::BluetoothChooser::DeviceInfo> vec; vec.reserve(device_map_.size()); for (const auto& it : device_map_) { DeviceInfo info = {it.first, it.second}; vec.push_back(info); } return vec; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,436
[Bug]: How can I cancel a bluetooth request?
### 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 23 ### What operating system are you using? Windows ### Operating System Version win10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior navigator.bluetooth.requestDevice return null after a while, if there is no device found. ### Actual Behavior navigator.bluetooth.requestDevice always bolck if there is no device ### Testcase Gist URL https://gist.github.com/a5d16943212179f7c033d5bd70531404 _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/37436
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-28T12:13:57Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.h
// Copyright (c) 2016 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_LIB_BLUETOOTH_CHOOSER_H_ #define ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_ #include <map> #include <string> #include <vector> #include "content/public/browser/bluetooth_chooser.h" #include "shell/browser/api/electron_api_web_contents.h" namespace electron { class BluetoothChooser : public content::BluetoothChooser { public: struct DeviceInfo { std::string device_id; std::u16string device_name; }; explicit BluetoothChooser(api::WebContents* contents, const EventHandler& handler); ~BluetoothChooser() override; // disable copy BluetoothChooser(const BluetoothChooser&) = delete; BluetoothChooser& operator=(const BluetoothChooser&) = delete; // content::BluetoothChooser: void SetAdapterPresence(AdapterPresence presence) override; void ShowDiscoveryState(DiscoveryState state) override; void AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) override; std::vector<DeviceInfo> GetDeviceList(); private: std::map<std::string, std::u16string> device_map_; api::WebContents* api_web_contents_; EventHandler event_handler_; int num_retries_ = 0; bool refreshing_ = false; bool rescan_ = false; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_LIB_BLUETOOTH_CHOOSER_H_
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
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.fromFrame(frame)` * `frame` WebFrameMain Returns `WebContents` | undefined - A WebContents instance with the given WebFrameMain, or `undefined` if there is no WebContents associated with the given WebFrameMain. ### `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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ Emitted when any frame (including main) starts navigating. #### Event: 'will-redirect' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. * `isMainFrame` boolean - True if the navigation is taking place in a main frame. * `frame` WebFrameMain - The frame to be navigated. * `initiator` WebFrameMain (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. via `window.open` with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted. * `url` string _Deprecated_ * `isInPlace` boolean _Deprecated_ * `isMainFrame` boolean _Deprecated_ * `frameProcessId` Integer _Deprecated_ * `frameRoutingId` Integer _Deprecated_ 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: 'input-event' Returns: * `event` Event * `inputEvent` [InputEvent](structures/input-event.md) Emitted when an input event is sent to the WebContents. See [InputEvent](structures/input-event.md) for details. #### 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-open-url' Returns: * `url` string - URL of the link that was clicked or selected. Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu. #### 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`](#contentsfindinpagetext-options) request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'audio-state-changed' Returns: * `event` Event<> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. #### 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 title='main.js' 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` [IpcMainEvent](structures/ipc-main-event.md) * `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` [IpcMainEvent](structures/ipc-main-event.md) * `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.close([opts])` * `opts` Object (optional) * `waitForBeforeUnload` boolean - if true, fire the `beforeunload` event before closing the page. If the page prevents the unload, the WebContents will not be closed. The [`will-prevent-unload`](#event-will-prevent-unload) will be fired if the page requests prevention of unload. Closes the page, as if the web content had called `window.close()`. If the page is successfully closed (i.e. the unload is not prevented by the page, or `waitForBeforeUnload` is false or unspecified), the WebContents will be destroyed and no longer usable. The [`destroyed`](#event-destroyed) event will be emitted. #### `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', outlivesOpener?: boolean, 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', outlivesOpener?: boolean, 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. By default, child windows are closed when their opener is closed. This can be changed by specifying `outlivesOpener: true`, in which case the opened window will not be closed when its opener is closed. 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`](#contentsfindinpagetext-options) 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, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. 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. 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. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `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 `A0`, `A1`, `A2`, `A3`, `A4`, `A5`, `A6`, `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 title='main.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. :::warning Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception. ::: For additional reading, refer to [Electron's IPC guide](../tutorial/ipc.md). #### `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. #### `contents.opener` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute. [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 [`MessagePortMain`]: message-port-main.md
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Web Bluetooth API</title> </head> <body> <h1>Web Bluetooth API</h1> <button id="clickme">Test Bluetooth</button> <p>Currently selected bluetooth device: <strong id="device-name""></strong></p> <script src="./renderer.js"></script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/main.js
const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() if (deviceList && deviceList.length > 0) { callback(deviceList[0].deviceId) } }) // Listen for a message from the renderer to get the response for the Bluetooth pairing. ipcMain.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow.webContents.send('bluetooth-pairing-request', details) }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/preload.js
const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
docs/fiddles/features/web-bluetooth/renderer.js
async function testIt() { const device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true }) document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}` } document.getElementById('clickme').addEventListener('click',testIt) window.electronAPI.bluetoothPairingRequest((event, details) => { const response = {} switch (details.pairingKind) { case 'confirm': { response.confirmed = confirm(`Do you want to connect to device ${details.deviceId}?`) break } case 'confirmPin': { response.confirmed = confirm(`Does the pin ${details.pin} match the pin displayed on device ${details.deviceId}?`) break } case 'providePin': { const pin = prompt(`Please provide a pin for ${details.deviceId}.`) if (pin) { response.pin = pin response.confirmed = true } else { response.confirmed = false } } } window.electronAPI.bluetoothPairingResponse(response) })
closed
electron/electron
https://github.com/electron/electron
37,090
[Bug]: Web Bluetooth: Always cancelled request after first dismiss
### 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 22.1.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Pro 22H2 ### What arch are you using? x64 ### Last Known Working Electron version None ### Expected Behavior Even if it didn't found any devices, after i dismiss the request, it should perform another scan next time i call requestDevice. ### Actual Behavior After first dismiss the requestDevice, all later navigator.bluetooth.requestDevice return User cancelled immediatly. ### Testcase Gist URL https://gist.github.com/111927e2d69b53c6c151eb6aa5070948 ### Additional Information I have create a simple tst code on Fiddle, see above. I have alreadly check #10763, who seem like having the same problem but somehow he never repoduce it anymore. But i think i found the issue. It's really simple to reproduce infact, just get "select-bluetooth-device" event, and run navigator.bluetooth.requestDevice({ filters: [{ services: [0xffff] }] }) in console, and just run it again, it will return user cancelled immediatly. In fact, there's kinda a way to prevent that happend, is to call the callback in "select-bluetooth-device" event with an empty string when you need to cancel the discovery. But, that's the main issue here, if there's no filtered device found at all, then you never get the callback function to call with an empty string. if then you dismiss the request, it will keep returning "user cancelled" immediatly everytime you call requesrDevice later. the Fiddle example is demonstrating this. click scan, if there's no device found, click cancel, console will prompt "User cancelled the requestDevice()". if you uncomment the "acceptAllDevices" in renderer.js, which will found all the device, will not have this problem. Is there a way to get the callback funtion? or a better way to cancel the discovery? Thank you.
https://github.com/electron/electron/issues/37090
https://github.com/electron/electron/pull/37601
42e7cd9b3f3e16d07f162716b4f1346e32004aec
6a6908c4c887c5f685f5e172ff01afc02ebcbc65
2023-02-01T06:01:03Z
c++
2023-03-27T13:31:15Z
shell/browser/lib/bluetooth_chooser.cc
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/lib/bluetooth_chooser.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_helper/dictionary.h" namespace gin { template <> struct Converter<electron::BluetoothChooser::DeviceInfo> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::BluetoothChooser::DeviceInfo& val) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("deviceName", val.device_name); dict.Set("deviceId", val.device_id); return gin::ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron { namespace { const int kMaxScanRetries = 5; void OnDeviceChosen(const content::BluetoothChooser::EventHandler& handler, const std::string& device_id) { if (device_id.empty()) { handler.Run(content::BluetoothChooserEvent::CANCELLED, device_id); } else { handler.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } // namespace BluetoothChooser::BluetoothChooser(api::WebContents* contents, const EventHandler& event_handler) : api_web_contents_(contents), event_handler_(event_handler) {} BluetoothChooser::~BluetoothChooser() { event_handler_.Reset(); } void BluetoothChooser::SetAdapterPresence(AdapterPresence presence) { switch (presence) { case AdapterPresence::ABSENT: case AdapterPresence::POWERED_OFF: // Chrome currently directs the user to system preferences // to grant bluetooth permission for this case, should we // do something similar ? // https://chromium-review.googlesource.com/c/chromium/src/+/2617129 case AdapterPresence::UNAUTHORIZED: event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case AdapterPresence::POWERED_ON: rescan_ = true; break; } } void BluetoothChooser::ShowDiscoveryState(DiscoveryState state) { switch (state) { case DiscoveryState::FAILED_TO_START: refreshing_ = false; event_handler_.Run(content::BluetoothChooserEvent::CANCELLED, ""); break; case DiscoveryState::IDLE: refreshing_ = false; if (device_map_.empty()) { auto event = ++num_retries_ > kMaxScanRetries ? content::BluetoothChooserEvent::CANCELLED : content::BluetoothChooserEvent::RESCAN; event_handler_.Run(event, ""); } else { bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); if (!prevent_default) { auto it = device_map_.begin(); auto device_id = it->first; event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } break; case DiscoveryState::DISCOVERING: // The first time this state fires is due to a rescan triggering so set a // flag to ignore devices if (rescan_ && !refreshing_) { refreshing_ = true; } else { // The second time this state fires we are now safe to pick a device refreshing_ = false; } break; } } void BluetoothChooser::AddOrUpdateDevice(const std::string& device_id, bool should_update_name, const std::u16string& device_name, bool is_gatt_connected, bool is_paired, int signal_strength_level) { if (refreshing_) { // If the list of bluetooth devices is currently being generated don't fire // an event return; } bool changed = false; auto entry = device_map_.find(device_id); if (entry == device_map_.end()) { device_map_[device_id] = device_name; changed = true; } else if (should_update_name) { entry->second = device_name; changed = true; } if (changed) { // Emit a select-bluetooth-device handler to allow for user to listen for // bluetooth device found. bool prevent_default = api_web_contents_->Emit( "select-bluetooth-device", GetDeviceList(), base::BindOnce(&OnDeviceChosen, event_handler_)); // If emit not implemented select first device that matches the filters // provided. if (!prevent_default) { event_handler_.Run(content::BluetoothChooserEvent::SELECTED, device_id); } } } std::vector<electron::BluetoothChooser::DeviceInfo> BluetoothChooser::GetDeviceList() { std::vector<electron::BluetoothChooser::DeviceInfo> vec; vec.reserve(device_map_.size()); for (const auto& it : device_map_) { DeviceInfo info = {it.first, it.second}; vec.push_back(info); } return vec; } } // namespace electron