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
38,941
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.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 22.0.0 or higher ### What operating system are you using? Windows ### Operating System Version windows 11 22h2 ### What arch are you using? x64 ### Last Known Working Electron version 21.4.4 ### Expected Behavior Not crash. ### Actual Behavior Crash. ### Testcase Gist URL https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52 ### Additional Information npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
https://github.com/electron/electron/issues/38941
https://github.com/electron/electron/pull/38996
5a77c75753f560bbc4fe6560441ba88433a561f8
c7a64ab994de826ed6e4c300cce75d9fd88efa20
2023-06-28T07:41:44Z
c++
2023-07-06T08:20:34Z
spec/fixtures/crash-cases/webview-remove-on-wc-close/webview.html
closed
electron/electron
https://github.com/electron/electron
38,991
[Bug]: Windows: Menu drop downs overlap application menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.1.1 ### Expected Behavior After clicking on an item in the application menu, the menu should open *below* that item. ### Actual Behavior The menu overlaps the clicked item. See screenshot below. This just doesn't look nice but also decreases the usability. ![Screenshot of Electron menu](https://github.com/electron/electron/assets/24460532/8041f5b7-b571-48a5-8bff-213a4ac4f7b9) ### Testcase Gist URL _No response_ ### Additional Information Electron versions between 26.0.0-alpha.1 and 26.0.0-alpha.7 display the menu as expected. 26.0.0-alpha.8 and newer also have this bug. I don't think it is necessary to upload a repro repo (ask for that, if I'm wrong). In Electron Fiddle, I just needed to select the right Electron version.
https://github.com/electron/electron/issues/38991
https://github.com/electron/electron/pull/38998
c7a64ab994de826ed6e4c300cce75d9fd88efa20
cc7d724a3b85a858044916e5a4b61269610cab09
2023-07-04T23:45:35Z
c++
2023-07-06T13:46:12Z
patches/chromium/fix_crash_on_nativetheme_change_during_context_menu_close.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 16 Jun 2023 11:15:57 +0200 Subject: fix: crash on nativeTheme change during context menu close Refs https://chromium-review.googlesource.com/c/chromium/src/+/4363385 Fixes a crash seen when trying to change nativeTheme source during a context menu close. This happens as a result of a change added in the above CL, which doesn't check whether or not the menu controller could possibly be null as can happen during a context menu close. This only affects Windows 11, as Bubble Border is only enabled there. This should be upstreamed, as other uses of MenuController in this file do check for menu controller being null. diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc index 76bb4863858fb1bde1288b3d1b1d07f151a2f801..f2ceb3b8d6cbcf4bb4af8b85573bba29a38e5abf 100644 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ b/ui/views/controls/menu/menu_scroll_view_container.cc @@ -402,8 +402,7 @@ void MenuScrollViewContainer::CreateDefaultBorder() { MenuController* menu_controller = content_view_->GetMenuItem()->GetMenuController(); const MenuConfig& menu_config = MenuConfig::instance(); - corner_radius_ = menu_config.CornerRadiusForMenu( - content_view_->GetMenuItem()->GetMenuController()); + corner_radius_ = menu_config.CornerRadiusForMenu(menu_controller); int padding = menu_config.use_outer_border && corner_radius_ > 0 ? kBorderPaddingDueToRoundedCorners : 0; @@ -418,8 +417,9 @@ void MenuScrollViewContainer::CreateDefaultBorder() { int bottom_inset = GetFootnote() ? 0 : vertical_inset; if (menu_config.use_outer_border) { - if (menu_config.use_bubble_border && (corner_radius_ > 0) && - !menu_controller->IsCombobox()) { + // Menu controller could be null during context menu being closed. + bool is_combobox = menu_controller && !menu_controller->IsCombobox(); + if (menu_config.use_bubble_border && (corner_radius_ > 0) && !is_combobox) { CreateBubbleBorder(); } else { gfx::Insets insets = gfx::Insets::TLBR(vertical_inset, horizontal_inset,
closed
electron/electron
https://github.com/electron/electron
38,732
[Bug]: Crash if theme is changed via application menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 24.5.0 ### Expected Behavior The application changes the theme, e.g. the application menu is colored accordingly and it doesn't crash. ### Actual Behavior As soon the theme is changed via the application menu, the application crashes. On the console appears following output: ``` [36016:0612/045936.512:ERROR:crashpad_client_win.cc(844)] not connected ``` ### Testcase Gist URL https://gist.github.com/c9e0ce78e7811ce716923f4ad7111c8c ### Additional Information Selecting the currently used theme has no effect. This bug was introduced with Electron 25.0.0-alpha.1 Electron 26.0.0-alpha.5 is still affected as are (probably) all versions in between (I didn't try all).
https://github.com/electron/electron/issues/38732
https://github.com/electron/electron/pull/38998
c7a64ab994de826ed6e4c300cce75d9fd88efa20
cc7d724a3b85a858044916e5a4b61269610cab09
2023-06-12T03:08:39Z
c++
2023-07-06T13:46:12Z
patches/chromium/fix_crash_on_nativetheme_change_during_context_menu_close.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 16 Jun 2023 11:15:57 +0200 Subject: fix: crash on nativeTheme change during context menu close Refs https://chromium-review.googlesource.com/c/chromium/src/+/4363385 Fixes a crash seen when trying to change nativeTheme source during a context menu close. This happens as a result of a change added in the above CL, which doesn't check whether or not the menu controller could possibly be null as can happen during a context menu close. This only affects Windows 11, as Bubble Border is only enabled there. This should be upstreamed, as other uses of MenuController in this file do check for menu controller being null. diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc index 76bb4863858fb1bde1288b3d1b1d07f151a2f801..f2ceb3b8d6cbcf4bb4af8b85573bba29a38e5abf 100644 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ b/ui/views/controls/menu/menu_scroll_view_container.cc @@ -402,8 +402,7 @@ void MenuScrollViewContainer::CreateDefaultBorder() { MenuController* menu_controller = content_view_->GetMenuItem()->GetMenuController(); const MenuConfig& menu_config = MenuConfig::instance(); - corner_radius_ = menu_config.CornerRadiusForMenu( - content_view_->GetMenuItem()->GetMenuController()); + corner_radius_ = menu_config.CornerRadiusForMenu(menu_controller); int padding = menu_config.use_outer_border && corner_radius_ > 0 ? kBorderPaddingDueToRoundedCorners : 0; @@ -418,8 +417,9 @@ void MenuScrollViewContainer::CreateDefaultBorder() { int bottom_inset = GetFootnote() ? 0 : vertical_inset; if (menu_config.use_outer_border) { - if (menu_config.use_bubble_border && (corner_radius_ > 0) && - !menu_controller->IsCombobox()) { + // Menu controller could be null during context menu being closed. + bool is_combobox = menu_controller && !menu_controller->IsCombobox(); + if (menu_config.use_bubble_border && (corner_radius_ > 0) && !is_combobox) { CreateBubbleBorder(); } else { gfx::Insets insets = gfx::Insets::TLBR(vertical_inset, horizontal_inset,
closed
electron/electron
https://github.com/electron/electron
38,991
[Bug]: Windows: Menu drop downs overlap application menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 25.1.1 ### Expected Behavior After clicking on an item in the application menu, the menu should open *below* that item. ### Actual Behavior The menu overlaps the clicked item. See screenshot below. This just doesn't look nice but also decreases the usability. ![Screenshot of Electron menu](https://github.com/electron/electron/assets/24460532/8041f5b7-b571-48a5-8bff-213a4ac4f7b9) ### Testcase Gist URL _No response_ ### Additional Information Electron versions between 26.0.0-alpha.1 and 26.0.0-alpha.7 display the menu as expected. 26.0.0-alpha.8 and newer also have this bug. I don't think it is necessary to upload a repro repo (ask for that, if I'm wrong). In Electron Fiddle, I just needed to select the right Electron version.
https://github.com/electron/electron/issues/38991
https://github.com/electron/electron/pull/38998
c7a64ab994de826ed6e4c300cce75d9fd88efa20
cc7d724a3b85a858044916e5a4b61269610cab09
2023-07-04T23:45:35Z
c++
2023-07-06T13:46:12Z
patches/chromium/fix_crash_on_nativetheme_change_during_context_menu_close.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 16 Jun 2023 11:15:57 +0200 Subject: fix: crash on nativeTheme change during context menu close Refs https://chromium-review.googlesource.com/c/chromium/src/+/4363385 Fixes a crash seen when trying to change nativeTheme source during a context menu close. This happens as a result of a change added in the above CL, which doesn't check whether or not the menu controller could possibly be null as can happen during a context menu close. This only affects Windows 11, as Bubble Border is only enabled there. This should be upstreamed, as other uses of MenuController in this file do check for menu controller being null. diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc index 76bb4863858fb1bde1288b3d1b1d07f151a2f801..f2ceb3b8d6cbcf4bb4af8b85573bba29a38e5abf 100644 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ b/ui/views/controls/menu/menu_scroll_view_container.cc @@ -402,8 +402,7 @@ void MenuScrollViewContainer::CreateDefaultBorder() { MenuController* menu_controller = content_view_->GetMenuItem()->GetMenuController(); const MenuConfig& menu_config = MenuConfig::instance(); - corner_radius_ = menu_config.CornerRadiusForMenu( - content_view_->GetMenuItem()->GetMenuController()); + corner_radius_ = menu_config.CornerRadiusForMenu(menu_controller); int padding = menu_config.use_outer_border && corner_radius_ > 0 ? kBorderPaddingDueToRoundedCorners : 0; @@ -418,8 +417,9 @@ void MenuScrollViewContainer::CreateDefaultBorder() { int bottom_inset = GetFootnote() ? 0 : vertical_inset; if (menu_config.use_outer_border) { - if (menu_config.use_bubble_border && (corner_radius_ > 0) && - !menu_controller->IsCombobox()) { + // Menu controller could be null during context menu being closed. + bool is_combobox = menu_controller && !menu_controller->IsCombobox(); + if (menu_config.use_bubble_border && (corner_radius_ > 0) && !is_combobox) { CreateBubbleBorder(); } else { gfx::Insets insets = gfx::Insets::TLBR(vertical_inset, horizontal_inset,
closed
electron/electron
https://github.com/electron/electron
38,732
[Bug]: Crash if theme is changed via application menu
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 22H2 ### What arch are you using? x64 ### Last Known Working Electron version 24.5.0 ### Expected Behavior The application changes the theme, e.g. the application menu is colored accordingly and it doesn't crash. ### Actual Behavior As soon the theme is changed via the application menu, the application crashes. On the console appears following output: ``` [36016:0612/045936.512:ERROR:crashpad_client_win.cc(844)] not connected ``` ### Testcase Gist URL https://gist.github.com/c9e0ce78e7811ce716923f4ad7111c8c ### Additional Information Selecting the currently used theme has no effect. This bug was introduced with Electron 25.0.0-alpha.1 Electron 26.0.0-alpha.5 is still affected as are (probably) all versions in between (I didn't try all).
https://github.com/electron/electron/issues/38732
https://github.com/electron/electron/pull/38998
c7a64ab994de826ed6e4c300cce75d9fd88efa20
cc7d724a3b85a858044916e5a4b61269610cab09
2023-06-12T03:08:39Z
c++
2023-07-06T13:46:12Z
patches/chromium/fix_crash_on_nativetheme_change_during_context_menu_close.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 16 Jun 2023 11:15:57 +0200 Subject: fix: crash on nativeTheme change during context menu close Refs https://chromium-review.googlesource.com/c/chromium/src/+/4363385 Fixes a crash seen when trying to change nativeTheme source during a context menu close. This happens as a result of a change added in the above CL, which doesn't check whether or not the menu controller could possibly be null as can happen during a context menu close. This only affects Windows 11, as Bubble Border is only enabled there. This should be upstreamed, as other uses of MenuController in this file do check for menu controller being null. diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc index 76bb4863858fb1bde1288b3d1b1d07f151a2f801..f2ceb3b8d6cbcf4bb4af8b85573bba29a38e5abf 100644 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ b/ui/views/controls/menu/menu_scroll_view_container.cc @@ -402,8 +402,7 @@ void MenuScrollViewContainer::CreateDefaultBorder() { MenuController* menu_controller = content_view_->GetMenuItem()->GetMenuController(); const MenuConfig& menu_config = MenuConfig::instance(); - corner_radius_ = menu_config.CornerRadiusForMenu( - content_view_->GetMenuItem()->GetMenuController()); + corner_radius_ = menu_config.CornerRadiusForMenu(menu_controller); int padding = menu_config.use_outer_border && corner_radius_ > 0 ? kBorderPaddingDueToRoundedCorners : 0; @@ -418,8 +417,9 @@ void MenuScrollViewContainer::CreateDefaultBorder() { int bottom_inset = GetFootnote() ? 0 : vertical_inset; if (menu_config.use_outer_border) { - if (menu_config.use_bubble_border && (corner_radius_ > 0) && - !menu_controller->IsCombobox()) { + // Menu controller could be null during context menu being closed. + bool is_combobox = menu_controller && !menu_controller->IsCombobox(); + if (menu_config.use_bubble_border && (corner_radius_ > 0) && !is_combobox) { CreateBubbleBorder(); } else { gfx::Insets insets = gfx::Insets::TLBR(vertical_inset, horizontal_inset,
closed
electron/electron
https://github.com/electron/electron
38,995
[Bug]: Notification auto adds the action button 'show' in MacOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.1 ### Expected Behavior Create a notification: `New Notification('title'); // note that there is no options.` The notification in the top-right screen should only show a popup with the title. <img width="364" alt="image" src="https://github.com/electron/electron/assets/28861842/2190fb95-4ffe-4ad4-b04f-b4e7ea51103a"> for bellow example, click the 'click me' button to execute `noti` fn ### Actual Behavior - The notification popup show with an action button named: 'show' when I hover the popup. - If I click, there is no action trigger <img width="369" alt="image" src="https://github.com/electron/electron/assets/28861842/7426041d-d1e4-4630-9666-c8124d820e8f"> ### Testcase Gist URL https://gist.github.com/319ccca16a8cd1ec6263adc2723e994e ### Additional Information I think this issue is caused by this commit: https://github.com/electron/electron/commit/8fb0f430301578ba94b175f0b097fb2752f5ddf9 `[notification_ setHasActionButton:false];` removed, but as my research, the default of this value is true. We need to set it to false in case there are no actions added https://developer.apple.com/documentation/foundation/nsusernotification/1411564-hasactionbutton
https://github.com/electron/electron/issues/38995
https://github.com/electron/electron/pull/38997
cc7d724a3b85a858044916e5a4b61269610cab09
a97028bacfba8c0416e02805897e89d1c013717c
2023-07-05T07:56:02Z
c++
2023-07-06T19:50:08Z
shell/browser/notifications/mac/cocoa_notification.mm
// 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/notifications/mac/cocoa_notification.h" #include <string> #include <utility> #include "base/logging.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/notifications/notification_presenter.h" #include "skia/ext/skia_utils_mac.h" namespace electron { CocoaNotification::CocoaNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} CocoaNotification::~CocoaNotification() { if (notification_) [NSUserNotificationCenter.defaultUserNotificationCenter removeDeliveredNotification:notification_]; } void CocoaNotification::Show(const NotificationOptions& options) { notification_.reset([[NSUserNotification alloc] init]); NSString* identifier = [NSString stringWithFormat:@"%@:notification:%@", [[NSBundle mainBundle] bundleIdentifier], [[NSUUID UUID] UUIDString]]; [notification_ setTitle:base::SysUTF16ToNSString(options.title)]; [notification_ setSubtitle:base::SysUTF16ToNSString(options.subtitle)]; [notification_ setInformativeText:base::SysUTF16ToNSString(options.msg)]; [notification_ setIdentifier:identifier]; if (getenv("ELECTRON_DEBUG_NOTIFICATIONS")) { LOG(INFO) << "Notification created (" << [identifier UTF8String] << ")"; } if (!options.icon.drawsNothing()) { NSImage* image = skia::SkBitmapToNSImageWithColorSpace( options.icon, base::mac::GetGenericRGBColorSpace()); [notification_ setContentImage:image]; } if (options.silent) { [notification_ setSoundName:nil]; } else if (options.sound.empty()) { [notification_ setSoundName:NSUserNotificationDefaultSoundName]; } else { [notification_ setSoundName:base::SysUTF16ToNSString(options.sound)]; } if (options.has_reply) { [notification_ setHasReplyButton:true]; [notification_ setResponsePlaceholder:base::SysUTF16ToNSString( options.reply_placeholder)]; } int i = 0; action_index_ = UINT_MAX; NSMutableArray* additionalActions = [[[NSMutableArray alloc] init] autorelease]; for (const auto& action : options.actions) { if (action.type == u"button") { // If the notification has both a reply and actions, // the reply takes precedence and the actions all // become additional actions. if (!options.has_reply && action_index_ == UINT_MAX) { // First button observed is the displayed action [notification_ setHasActionButton:true]; [notification_ setActionButtonTitle:base::SysUTF16ToNSString(action.text)]; action_index_ = i; } else { // All of the rest are appended to the list of additional actions NSString* actionIdentifier = [NSString stringWithFormat:@"%@Action%d", identifier, i]; NSUserNotificationAction* notificationAction = [NSUserNotificationAction actionWithIdentifier:actionIdentifier title:base::SysUTF16ToNSString(action.text)]; [additionalActions addObject:notificationAction]; additional_action_indices_.insert( std::make_pair(base::SysNSStringToUTF8(actionIdentifier), i)); } } i++; } if ([additionalActions count] > 0) { [notification_ setAdditionalActions:additionalActions]; } if (!options.close_button_text.empty()) { [notification_ setOtherButtonTitle:base::SysUTF16ToNSString( options.close_button_text)]; } [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification_]; } void CocoaNotification::Dismiss() { if (notification_) [NSUserNotificationCenter.defaultUserNotificationCenter removeDeliveredNotification:notification_]; NotificationDismissed(); notification_.reset(nil); } void CocoaNotification::NotificationDisplayed() { if (delegate()) delegate()->NotificationDisplayed(); this->LogAction("displayed"); } void CocoaNotification::NotificationReplied(const std::string& reply) { if (delegate()) delegate()->NotificationReplied(reply); this->LogAction("replied to"); } void CocoaNotification::NotificationActivated() { if (delegate()) delegate()->NotificationAction(action_index_); this->LogAction("button clicked"); } void CocoaNotification::NotificationActivated( NSUserNotificationAction* action) { if (delegate()) { unsigned index = action_index_; std::string identifier = base::SysNSStringToUTF8(action.identifier); for (const auto& it : additional_action_indices_) { if (it.first == identifier) { index = it.second; break; } } delegate()->NotificationAction(index); } this->LogAction("button clicked"); } void CocoaNotification::NotificationDismissed() { if (delegate()) delegate()->NotificationClosed(); this->LogAction("dismissed"); } void CocoaNotification::LogAction(const char* action) { if (getenv("ELECTRON_DEBUG_NOTIFICATIONS") && notification_) { NSString* identifier = [notification_ valueForKey:@"identifier"]; DCHECK(identifier); LOG(INFO) << "Notification " << action << " (" << [identifier UTF8String] << ")"; } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,995
[Bug]: Notification auto adds the action button 'show' in MacOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? macOS ### Operating System Version Ventura 13.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 22.3.1 ### Expected Behavior Create a notification: `New Notification('title'); // note that there is no options.` The notification in the top-right screen should only show a popup with the title. <img width="364" alt="image" src="https://github.com/electron/electron/assets/28861842/2190fb95-4ffe-4ad4-b04f-b4e7ea51103a"> for bellow example, click the 'click me' button to execute `noti` fn ### Actual Behavior - The notification popup show with an action button named: 'show' when I hover the popup. - If I click, there is no action trigger <img width="369" alt="image" src="https://github.com/electron/electron/assets/28861842/7426041d-d1e4-4630-9666-c8124d820e8f"> ### Testcase Gist URL https://gist.github.com/319ccca16a8cd1ec6263adc2723e994e ### Additional Information I think this issue is caused by this commit: https://github.com/electron/electron/commit/8fb0f430301578ba94b175f0b097fb2752f5ddf9 `[notification_ setHasActionButton:false];` removed, but as my research, the default of this value is true. We need to set it to false in case there are no actions added https://developer.apple.com/documentation/foundation/nsusernotification/1411564-hasactionbutton
https://github.com/electron/electron/issues/38995
https://github.com/electron/electron/pull/38997
cc7d724a3b85a858044916e5a4b61269610cab09
a97028bacfba8c0416e02805897e89d1c013717c
2023-07-05T07:56:02Z
c++
2023-07-06T19:50:08Z
shell/browser/notifications/mac/cocoa_notification.mm
// 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/notifications/mac/cocoa_notification.h" #include <string> #include <utility> #include "base/logging.h" #include "base/mac/mac_util.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/notifications/notification_presenter.h" #include "skia/ext/skia_utils_mac.h" namespace electron { CocoaNotification::CocoaNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} CocoaNotification::~CocoaNotification() { if (notification_) [NSUserNotificationCenter.defaultUserNotificationCenter removeDeliveredNotification:notification_]; } void CocoaNotification::Show(const NotificationOptions& options) { notification_.reset([[NSUserNotification alloc] init]); NSString* identifier = [NSString stringWithFormat:@"%@:notification:%@", [[NSBundle mainBundle] bundleIdentifier], [[NSUUID UUID] UUIDString]]; [notification_ setTitle:base::SysUTF16ToNSString(options.title)]; [notification_ setSubtitle:base::SysUTF16ToNSString(options.subtitle)]; [notification_ setInformativeText:base::SysUTF16ToNSString(options.msg)]; [notification_ setIdentifier:identifier]; if (getenv("ELECTRON_DEBUG_NOTIFICATIONS")) { LOG(INFO) << "Notification created (" << [identifier UTF8String] << ")"; } if (!options.icon.drawsNothing()) { NSImage* image = skia::SkBitmapToNSImageWithColorSpace( options.icon, base::mac::GetGenericRGBColorSpace()); [notification_ setContentImage:image]; } if (options.silent) { [notification_ setSoundName:nil]; } else if (options.sound.empty()) { [notification_ setSoundName:NSUserNotificationDefaultSoundName]; } else { [notification_ setSoundName:base::SysUTF16ToNSString(options.sound)]; } if (options.has_reply) { [notification_ setHasReplyButton:true]; [notification_ setResponsePlaceholder:base::SysUTF16ToNSString( options.reply_placeholder)]; } int i = 0; action_index_ = UINT_MAX; NSMutableArray* additionalActions = [[[NSMutableArray alloc] init] autorelease]; for (const auto& action : options.actions) { if (action.type == u"button") { // If the notification has both a reply and actions, // the reply takes precedence and the actions all // become additional actions. if (!options.has_reply && action_index_ == UINT_MAX) { // First button observed is the displayed action [notification_ setHasActionButton:true]; [notification_ setActionButtonTitle:base::SysUTF16ToNSString(action.text)]; action_index_ = i; } else { // All of the rest are appended to the list of additional actions NSString* actionIdentifier = [NSString stringWithFormat:@"%@Action%d", identifier, i]; NSUserNotificationAction* notificationAction = [NSUserNotificationAction actionWithIdentifier:actionIdentifier title:base::SysUTF16ToNSString(action.text)]; [additionalActions addObject:notificationAction]; additional_action_indices_.insert( std::make_pair(base::SysNSStringToUTF8(actionIdentifier), i)); } } i++; } if ([additionalActions count] > 0) { [notification_ setAdditionalActions:additionalActions]; } if (!options.close_button_text.empty()) { [notification_ setOtherButtonTitle:base::SysUTF16ToNSString( options.close_button_text)]; } [NSUserNotificationCenter.defaultUserNotificationCenter deliverNotification:notification_]; } void CocoaNotification::Dismiss() { if (notification_) [NSUserNotificationCenter.defaultUserNotificationCenter removeDeliveredNotification:notification_]; NotificationDismissed(); notification_.reset(nil); } void CocoaNotification::NotificationDisplayed() { if (delegate()) delegate()->NotificationDisplayed(); this->LogAction("displayed"); } void CocoaNotification::NotificationReplied(const std::string& reply) { if (delegate()) delegate()->NotificationReplied(reply); this->LogAction("replied to"); } void CocoaNotification::NotificationActivated() { if (delegate()) delegate()->NotificationAction(action_index_); this->LogAction("button clicked"); } void CocoaNotification::NotificationActivated( NSUserNotificationAction* action) { if (delegate()) { unsigned index = action_index_; std::string identifier = base::SysNSStringToUTF8(action.identifier); for (const auto& it : additional_action_indices_) { if (it.first == identifier) { index = it.second; break; } } delegate()->NotificationAction(index); } this->LogAction("button clicked"); } void CocoaNotification::NotificationDismissed() { if (delegate()) delegate()->NotificationClosed(); this->LogAction("dismissed"); } void CocoaNotification::LogAction(const char* action) { if (getenv("ELECTRON_DEBUG_NOTIFICATIONS") && notification_) { NSString* identifier = [notification_ valueForKey:@"identifier"]; DCHECK(identifier); LOG(INFO) << "Notification " << action << " (" << [identifier UTF8String] << ")"; } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,975
[Bug]: error callback on print
### 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 24.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I have no paper in my printer and when I want print it document stay in queue and electron window.contents.print(options, (success, errorType) => { console.log(success) console.log(errorType) }) errorType is empty and success return true but i am not printed anything because no paper if my document not printing success have to return false and if my document in a queue errorType have to return some information about it ### Actual Behavior success true and no errorType ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38975
https://github.com/electron/electron/pull/38976
c7bdd907d7e1fdcb7741de02f5ca23d47a436437
117a700724074dfc62649e3e561ff284f07e7cae
2023-07-03T13:55:41Z
c++
2023-07-10T13:26:29Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/BUILD.gn b/BUILD.gn index 08dae2813066a22c16c7cd524fa2c9747bf6ff40..de224c63c242c38b9d12c445a46483a1b2778944 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -971,7 +971,6 @@ if (is_win) { "//media:media_unittests", "//media/midi:midi_unittests", "//net:net_unittests", - "//printing:printing_unittests", "//sql:sql_unittests", "//third_party/breakpad:symupload($host_toolchain)", "//ui/base:ui_base_unittests", @@ -980,6 +979,10 @@ if (is_win) { "//ui/views:views_unittests", "//url:url_unittests", ] + + if (enable_printing) { + deps += [ "//printing:printing_unittests" ] + } } } diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) { auto* rfh = content::RenderFrameHost::FromID(rfh_id); return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query, #if BUILDFLAG(IS_WIN) pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count); - PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) { - use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled); - } + // TODO(codebytere): should we enable this later? + use_skia_ = false; #endif auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings), @@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c976fb2a814e4ff09650982034371e40d1ab77bc..c9115c7bbead588f3099bb194eb293b0e78ad211 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -23,7 +23,9 @@ #include "chrome/browser/bad_message.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" +#if 0 // Electron does not use Chrome error dialogs #include "chrome/browser/printing/print_error_dialog.h" +#endif #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_view_manager_common.h" @@ -83,6 +85,20 @@ namespace printing { namespace { +std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) { + if (status == PrintViewManager::PrintStatus::kInvalid) { + return "Invalid printer settings"; + } else if (status == PrintViewManager::PrintStatus::kCanceled) { + return "Print job canceled"; + } else if (status == PrintViewManager::PrintStatus::kFailed) { + return "Print job failed"; + } + return ""; +} + +using PrintSettingsCallback = + base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; + void OnDidGetDefaultPrintSettings( scoped_refptr<PrintQueriesQueue> queue, bool want_pdf_settings, @@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (printer_query->last_status() != mojom::ResultCode::kSuccess) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings( params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params)) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -122,7 +142,8 @@ void OnDidScriptedPrint( if (printer_query->last_status() != mojom::ResultCode::kSuccess || !printer_query->settings().dpi()) { - std::move(callback).Run(nullptr); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; + std::move(callback).Run(nullptr, canceled); return; } @@ -132,12 +153,12 @@ void OnDidScriptedPrint( params->params.get()); params->params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params->params)) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } params->pages = printer_query->settings().ranges(); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), false); queue->QueuePrinterQuery(std::move(printer_query)); } @@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); + printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -199,12 +222,20 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() { } #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value::Dict settings, + CompletionCallback callback) { if (!StartPrintCommon(rfh)) { return false; } +#if 0 CompletePrintNow(rfh); +#endif + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); return true; } @@ -313,12 +344,13 @@ void PrintViewManagerBase::OnDidUpdatePrintableArea( } PRINTER_LOG(EVENT) << "Paper printable area updated for vendor id " << print_settings->requested_media().vendor_id; - CompleteUpdatePrintSettings(std::move(job_settings), + CompleteUpdatePrintSettings(nullptr /* printer_query */, std::move(job_settings), std::move(print_settings), std::move(callback)); } #endif void PrintViewManagerBase::CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback) { @@ -326,7 +358,8 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( settings->pages = GetPageRangesFromJobSettings(job_settings); settings->params = mojom::PrintParams::New(); RenderParamsFromPrintSettings(*print_settings, settings->params.get()); - settings->params->document_cookie = PrintSettings::NewCookie(); + settings->params->document_cookie = printer_query ? printer_query->cookie() + : PrintSettings::NewCookie(); if (!PrintMsgPrintParamsIsValid(*settings->params)) { mojom::PrinterType printer_type = static_cast<mojom::PrinterType>( *job_settings.FindInt(kSettingPrinterType)); @@ -338,6 +371,10 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( return; } + if (printer_query && printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(std::move(printer_query)); + } + set_cookie(settings->params->document_cookie); std::move(callback).Run(std::move(settings)); } @@ -441,7 +478,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -456,12 +494,15 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + if (params) { set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } else { set_cookie(0); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); } } @@ -598,10 +639,12 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), nullptr); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) @@ -652,10 +695,12 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { std::move(callback).Run(nullptr); return; } +#endif // Printing is always enabled. absl::optional<int> printer_type_value = job_settings.FindInt(kSettingPrinterType); @@ -666,6 +711,7 @@ void PrintViewManagerBase::UpdatePrintSettings( mojom::PrinterType printer_type = static_cast<mojom::PrinterType>(*printer_type_value); +#if 0 // Printing is always enabled. if (printer_type != mojom::PrinterType::kExtension && printer_type != mojom::PrinterType::kPdf && printer_type != mojom::PrinterType::kLocal) { @@ -685,6 +731,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif // Printing is always enabled. std::unique_ptr<PrintSettings> print_settings = PrintSettingsFromJobSettings(job_settings); @@ -704,6 +751,16 @@ void PrintViewManagerBase::UpdatePrintSettings( } } + std::unique_ptr<PrinterQuery> query = + queue_->CreatePrinterQuery(GetCurrentTargetFrame()->GetGlobalId()); + auto* query_ptr = query.get(); + query_ptr->SetSettings( + job_settings.Clone(), + base::BindOnce(&PrintViewManagerBase::CompleteUpdatePrintSettings, + weak_ptr_factory_.GetWeakPtr(), std::move(query), + std::move(job_settings), std::move(print_settings), + std::move(callback))); + #if BUILDFLAG(IS_WIN) // TODO(crbug.com/1424368): Remove this if the printable areas can be made // fully available from `PrintBackend::GetPrinterSemanticCapsAndDefaults()` @@ -726,15 +783,13 @@ void PrintViewManagerBase::UpdatePrintSettings( } #endif - CompleteUpdatePrintSettings(std::move(job_settings), - std::move(print_settings), std::move(callback)); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerBase::IsPrintingEnabled( IsPrintingEnabledCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::move(callback).Run(printing_enabled_.GetValue()); + std::move(callback).Run(true); } void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, @@ -750,14 +805,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !query_with_ui_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #endif @@ -792,6 +847,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); +#if 0 // Electron does not use Chromium error dialogs // `PrintingFailed()` can occur because asynchronous compositing results // don't complete until after a print job has already failed and been // destroyed. In such cases the error notification to the user will @@ -801,7 +857,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, print_job_->document()->cookie() == cookie) { ShowPrintErrorDialogForGenericError(); } - +#endif ReleasePrinterQuery(); } @@ -813,15 +869,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) { test_observers_.RemoveObserver(&observer); } +void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + printing_status_ = PrintStatus::kInvalid; + TerminatePrintJob(true); + } +} + void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf() && !render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) { GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer(); } +#endif } void PrintViewManagerBase::RenderFrameDeleted( @@ -873,7 +938,12 @@ void PrintViewManagerBase::OnJobDone() { // Printing is done, we don't need it anymore. // print_job_->is_job_pending() may still be true, depending on the order // of object registration. - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; + ReleasePrintJob(); +} + +void PrintViewManagerBase::UserInitCanceled() { + printing_status_ = PrintStatus::kCanceled; ReleasePrintJob(); } @@ -882,9 +952,10 @@ void PrintViewManagerBase::OnCanceling() { } void PrintViewManagerBase::OnFailed() { +#if 0 // Electron does not use Chromium error dialogs if (!canceling_job_) ShowPrintErrorDialogForGenericError(); - +#endif TerminatePrintJob(true); } @@ -894,7 +965,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { // Is the document already complete? if (print_job_->document() && print_job_->document()->IsComplete()) { - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; return true; } @@ -942,7 +1013,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current `print_job_`. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -963,7 +1037,7 @@ bool PrintViewManagerBase::CreateNewPrintJob( #endif print_job_->AddObserver(*this); - printing_succeeded_ = false; + printing_status_ = PrintStatus::kFailed; return true; } @@ -1031,6 +1105,11 @@ void PrintViewManagerBase::ReleasePrintJob() { } #endif + if (!callback_.is_null()) { + bool success = printing_status_ == PrintStatus::kSucceeded; + std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_)); + } + if (!print_job_) return; @@ -1038,7 +1117,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // printing_rfh_ should only ever point to a RenderFrameHost with a live // RenderFrame. DCHECK(rfh->IsRenderFrameLive()); - GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); + GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded); } print_job_->RemoveObserver(*this); @@ -1080,7 +1159,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1224,7 +1303,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() { } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict()); for (auto& observer : GetTestObservers()) { observer.OnPrintNow(rfh); @@ -1274,7 +1353,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis( set_analyzing_content(/*analyzing*/ false); if (!allowed || !printing_rfh_ || IsCrashed() || !printing_rfh_->IsRenderFrameLive()) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback)); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 4ae11ba1c9cabb659910271c1ef20ff08a67df67..bbc77212abe5e73b58605058d7a3c49cfa1c003f 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -47,6 +47,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value::Dict settings = {}, + CompletionCallback callback = {}); // Like PrintNow(), but for the node under the context menu, instead of the // entire frame. @@ -136,8 +141,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void ScriptedPrint(mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -145,6 +152,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void AddTestObserver(TestObserver& observer); void RemoveTestObserver(TestObserver& observer); + enum class PrintStatus { + kSucceeded, + kCanceled, + kFailed, + kInvalid, + kUnknown + }; + protected: explicit PrintViewManagerBase(content::WebContents* web_contents); @@ -272,6 +287,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { bool success); #endif void CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback); @@ -301,7 +317,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -371,8 +388,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. - bool printing_succeeded_ = false; + PrintStatus printing_status_ = PrintStatus::kUnknown; // Indication that the job is getting canceled. bool canceling_job_ = false; diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc @@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode result_code = printing_context_->UseDefaultSettings(); + if (result_code == mojom::ResultCode::kSuccess) + result_code = printing_context_->UpdatePrintSettings(std::move(new_settings)); + InvokeSettingsCallback(std::move(callback), result_code); } - - InvokeSettingsCallback(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) { diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; void PrintForSystemDialog() override; diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644 --- a/components/printing/browser/print_manager.cc +++ b/components/printing/browser/print_manager.cc @@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) { std::move(callback).Run(true); } +void PrintManager::ShowInvalidPrinterSettingsError() {} + void PrintManager::PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) { // Note: Not redundant with cookie checks in the same method in other parts of diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644 --- a/components/printing/browser/print_manager.h +++ b/components/printing/browser/print_manager.h @@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver, DidPrintDocumentCallback callback) override; void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void DidShowPrintDialog() override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index c97825d05cb7d132c9af489998f4ed8c32603c00..fde20b8a6c4811ce728abfee26b2ab7b53027a94 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -296,7 +296,7 @@ union PrintWithParamsResult { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -390,7 +390,10 @@ interface PrintManagerHost { // UI to the user to select the final print settings. If the user cancels or // an error occurs, return null. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled); + + // Tells the browser that there are invalid printer settings. + ShowInvalidPrinterSettingsError(); // Tells the browser printing failed. PrintingFailed(int32 cookie, PrintFailureReason reason); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 5d5144737eace87832ab5c44cd8e2bfdeda5dec2..d9a9b65da336f31f4d302f5363737263d30aea4e 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -45,6 +45,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" @@ -1344,7 +1345,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::Value::Dict() /* new_settings */); if (!weak_this) return; @@ -1375,7 +1377,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1390,7 +1392,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1469,7 +1471,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::Value::Dict()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1520,6 +1523,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2130,7 +2135,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::Value::Dict() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2145,7 +2151,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2153,7 +2161,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2172,8 +2180,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2406,35 +2421,47 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + base::Value::Dict new_settings) { // Reset to default values. ignore_css_margins_ = false; - mojom::PrintPagesParams settings; - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); + mojom::PrintPagesParamsPtr settings; + if (new_settings.empty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + GetPrintManagerHost()->UpdatePrintSettings( + std::move(new_settings), &settings); + } // Check if the printer returned any settings, if the settings are null, // assume there are no printer drivers configured. So safely terminate. - if (!settings.params) { + if (!settings || !settings->params) { // Caller will reset `print_pages_params_`. return false; } - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return true; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + base::Value::Dict settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) { // Browser triggered this code path. It already knows about the failure. notify_browser_of_print_failure_ = false; + GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; } @@ -2538,7 +2565,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 0fea424325081a0ef6720000841ea321b89024d0..c700de4b81fc0c157946e76faedaca6b59aeac0c 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -247,7 +247,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -317,7 +317,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -326,12 +328,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + base::Value::Dict new_settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + base::Value::Dict settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 853c976d87eb2bc571a270bfe2ca5922ed21a6ee..723e937150ce59cf72cc5800ca2af82b0686a534 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn @@ -2905,8 +2905,9 @@ source_set("browser") { "//ppapi/shared_impl", ] - assert(enable_printing) - deps += [ "//printing" ] + if (enable_printing) { + deps += [ "//printing" ] + } if (is_chromeos) { sources += [ diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING) diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644 --- a/sandbox/policy/mac/sandbox_mac.mm +++ b/sandbox/policy/mac/sandbox_mac.mm @@ -41,6 +41,10 @@ #error "This file requires ARC support." #endif +#if BUILDFLAG(ENABLE_PRINTING) +#include "sandbox/policy/mac/print_backend.sb.h" +#endif + namespace sandbox::policy { base::FilePath GetCanonicalPath(const base::FilePath& path) {
closed
electron/electron
https://github.com/electron/electron
38,944
[Bug]: print() crashes on Windows, but works on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior webContents.print() should work and print page:) ### Actual Behavior in doesnt. When I call print(), app crashes silently. I can't catch any logs, even with process uncaughtException/unhandledRejection events. ### Testcase Gist URL _No response_ ### Additional Information I have created new empty project to test this bug. I have empty project with only one window. I just load image to the window and try to print it. ``` const createWindow = () => { const mainWindow = new BrowserWindow({ width: 800, height: 600, }); mainWindow.loadURL( "https://www.kasandbox.org/programming-images/avatars/leaf-blue.png" ); mainWindow.webContents.openDevTools(); mainWindow.webContents.on("did-finish-load", () => { console.log("did-finish-load"); mainWindow.webContents.print({ // silent: true, // deviceName: "Xprinter XP-365B", }); }); }; ``` I have tested it in different environments and different electron version (including latest ^26.0.0-beta.1). I works on macOS and always crashes on Windows (I've tried different versions: win 10, win 11, parallels, etc). Can you give me an advice, how it can be fixed?
https://github.com/electron/electron/issues/38944
https://github.com/electron/electron/pull/38976
c7bdd907d7e1fdcb7741de02f5ca23d47a436437
117a700724074dfc62649e3e561ff284f07e7cae
2023-06-28T23:10:46Z
c++
2023-07-10T13:26:29Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/BUILD.gn b/BUILD.gn index 08dae2813066a22c16c7cd524fa2c9747bf6ff40..de224c63c242c38b9d12c445a46483a1b2778944 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -971,7 +971,6 @@ if (is_win) { "//media:media_unittests", "//media/midi:midi_unittests", "//net:net_unittests", - "//printing:printing_unittests", "//sql:sql_unittests", "//third_party/breakpad:symupload($host_toolchain)", "//ui/base:ui_base_unittests", @@ -980,6 +979,10 @@ if (is_win) { "//ui/views:views_unittests", "//url:url_unittests", ] + + if (enable_printing) { + deps += [ "//printing:printing_unittests" ] + } } } diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) { auto* rfh = content::RenderFrameHost::FromID(rfh_id); return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query, #if BUILDFLAG(IS_WIN) pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count); - PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) { - use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled); - } + // TODO(codebytere): should we enable this later? + use_skia_ = false; #endif auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings), @@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c976fb2a814e4ff09650982034371e40d1ab77bc..c9115c7bbead588f3099bb194eb293b0e78ad211 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -23,7 +23,9 @@ #include "chrome/browser/bad_message.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" +#if 0 // Electron does not use Chrome error dialogs #include "chrome/browser/printing/print_error_dialog.h" +#endif #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_view_manager_common.h" @@ -83,6 +85,20 @@ namespace printing { namespace { +std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) { + if (status == PrintViewManager::PrintStatus::kInvalid) { + return "Invalid printer settings"; + } else if (status == PrintViewManager::PrintStatus::kCanceled) { + return "Print job canceled"; + } else if (status == PrintViewManager::PrintStatus::kFailed) { + return "Print job failed"; + } + return ""; +} + +using PrintSettingsCallback = + base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; + void OnDidGetDefaultPrintSettings( scoped_refptr<PrintQueriesQueue> queue, bool want_pdf_settings, @@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (printer_query->last_status() != mojom::ResultCode::kSuccess) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings( params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params)) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -122,7 +142,8 @@ void OnDidScriptedPrint( if (printer_query->last_status() != mojom::ResultCode::kSuccess || !printer_query->settings().dpi()) { - std::move(callback).Run(nullptr); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; + std::move(callback).Run(nullptr, canceled); return; } @@ -132,12 +153,12 @@ void OnDidScriptedPrint( params->params.get()); params->params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params->params)) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } params->pages = printer_query->settings().ranges(); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), false); queue->QueuePrinterQuery(std::move(printer_query)); } @@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); + printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -199,12 +222,20 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() { } #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value::Dict settings, + CompletionCallback callback) { if (!StartPrintCommon(rfh)) { return false; } +#if 0 CompletePrintNow(rfh); +#endif + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); return true; } @@ -313,12 +344,13 @@ void PrintViewManagerBase::OnDidUpdatePrintableArea( } PRINTER_LOG(EVENT) << "Paper printable area updated for vendor id " << print_settings->requested_media().vendor_id; - CompleteUpdatePrintSettings(std::move(job_settings), + CompleteUpdatePrintSettings(nullptr /* printer_query */, std::move(job_settings), std::move(print_settings), std::move(callback)); } #endif void PrintViewManagerBase::CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback) { @@ -326,7 +358,8 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( settings->pages = GetPageRangesFromJobSettings(job_settings); settings->params = mojom::PrintParams::New(); RenderParamsFromPrintSettings(*print_settings, settings->params.get()); - settings->params->document_cookie = PrintSettings::NewCookie(); + settings->params->document_cookie = printer_query ? printer_query->cookie() + : PrintSettings::NewCookie(); if (!PrintMsgPrintParamsIsValid(*settings->params)) { mojom::PrinterType printer_type = static_cast<mojom::PrinterType>( *job_settings.FindInt(kSettingPrinterType)); @@ -338,6 +371,10 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( return; } + if (printer_query && printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(std::move(printer_query)); + } + set_cookie(settings->params->document_cookie); std::move(callback).Run(std::move(settings)); } @@ -441,7 +478,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -456,12 +494,15 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + if (params) { set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } else { set_cookie(0); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); } } @@ -598,10 +639,12 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), nullptr); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) @@ -652,10 +695,12 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { std::move(callback).Run(nullptr); return; } +#endif // Printing is always enabled. absl::optional<int> printer_type_value = job_settings.FindInt(kSettingPrinterType); @@ -666,6 +711,7 @@ void PrintViewManagerBase::UpdatePrintSettings( mojom::PrinterType printer_type = static_cast<mojom::PrinterType>(*printer_type_value); +#if 0 // Printing is always enabled. if (printer_type != mojom::PrinterType::kExtension && printer_type != mojom::PrinterType::kPdf && printer_type != mojom::PrinterType::kLocal) { @@ -685,6 +731,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif // Printing is always enabled. std::unique_ptr<PrintSettings> print_settings = PrintSettingsFromJobSettings(job_settings); @@ -704,6 +751,16 @@ void PrintViewManagerBase::UpdatePrintSettings( } } + std::unique_ptr<PrinterQuery> query = + queue_->CreatePrinterQuery(GetCurrentTargetFrame()->GetGlobalId()); + auto* query_ptr = query.get(); + query_ptr->SetSettings( + job_settings.Clone(), + base::BindOnce(&PrintViewManagerBase::CompleteUpdatePrintSettings, + weak_ptr_factory_.GetWeakPtr(), std::move(query), + std::move(job_settings), std::move(print_settings), + std::move(callback))); + #if BUILDFLAG(IS_WIN) // TODO(crbug.com/1424368): Remove this if the printable areas can be made // fully available from `PrintBackend::GetPrinterSemanticCapsAndDefaults()` @@ -726,15 +783,13 @@ void PrintViewManagerBase::UpdatePrintSettings( } #endif - CompleteUpdatePrintSettings(std::move(job_settings), - std::move(print_settings), std::move(callback)); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerBase::IsPrintingEnabled( IsPrintingEnabledCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::move(callback).Run(printing_enabled_.GetValue()); + std::move(callback).Run(true); } void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, @@ -750,14 +805,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !query_with_ui_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #endif @@ -792,6 +847,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); +#if 0 // Electron does not use Chromium error dialogs // `PrintingFailed()` can occur because asynchronous compositing results // don't complete until after a print job has already failed and been // destroyed. In such cases the error notification to the user will @@ -801,7 +857,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, print_job_->document()->cookie() == cookie) { ShowPrintErrorDialogForGenericError(); } - +#endif ReleasePrinterQuery(); } @@ -813,15 +869,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) { test_observers_.RemoveObserver(&observer); } +void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + printing_status_ = PrintStatus::kInvalid; + TerminatePrintJob(true); + } +} + void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf() && !render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) { GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer(); } +#endif } void PrintViewManagerBase::RenderFrameDeleted( @@ -873,7 +938,12 @@ void PrintViewManagerBase::OnJobDone() { // Printing is done, we don't need it anymore. // print_job_->is_job_pending() may still be true, depending on the order // of object registration. - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; + ReleasePrintJob(); +} + +void PrintViewManagerBase::UserInitCanceled() { + printing_status_ = PrintStatus::kCanceled; ReleasePrintJob(); } @@ -882,9 +952,10 @@ void PrintViewManagerBase::OnCanceling() { } void PrintViewManagerBase::OnFailed() { +#if 0 // Electron does not use Chromium error dialogs if (!canceling_job_) ShowPrintErrorDialogForGenericError(); - +#endif TerminatePrintJob(true); } @@ -894,7 +965,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { // Is the document already complete? if (print_job_->document() && print_job_->document()->IsComplete()) { - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; return true; } @@ -942,7 +1013,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current `print_job_`. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -963,7 +1037,7 @@ bool PrintViewManagerBase::CreateNewPrintJob( #endif print_job_->AddObserver(*this); - printing_succeeded_ = false; + printing_status_ = PrintStatus::kFailed; return true; } @@ -1031,6 +1105,11 @@ void PrintViewManagerBase::ReleasePrintJob() { } #endif + if (!callback_.is_null()) { + bool success = printing_status_ == PrintStatus::kSucceeded; + std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_)); + } + if (!print_job_) return; @@ -1038,7 +1117,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // printing_rfh_ should only ever point to a RenderFrameHost with a live // RenderFrame. DCHECK(rfh->IsRenderFrameLive()); - GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); + GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded); } print_job_->RemoveObserver(*this); @@ -1080,7 +1159,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1224,7 +1303,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() { } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict()); for (auto& observer : GetTestObservers()) { observer.OnPrintNow(rfh); @@ -1274,7 +1353,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis( set_analyzing_content(/*analyzing*/ false); if (!allowed || !printing_rfh_ || IsCrashed() || !printing_rfh_->IsRenderFrameLive()) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback)); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 4ae11ba1c9cabb659910271c1ef20ff08a67df67..bbc77212abe5e73b58605058d7a3c49cfa1c003f 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -47,6 +47,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value::Dict settings = {}, + CompletionCallback callback = {}); // Like PrintNow(), but for the node under the context menu, instead of the // entire frame. @@ -136,8 +141,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void ScriptedPrint(mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -145,6 +152,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void AddTestObserver(TestObserver& observer); void RemoveTestObserver(TestObserver& observer); + enum class PrintStatus { + kSucceeded, + kCanceled, + kFailed, + kInvalid, + kUnknown + }; + protected: explicit PrintViewManagerBase(content::WebContents* web_contents); @@ -272,6 +287,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { bool success); #endif void CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback); @@ -301,7 +317,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -371,8 +388,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. - bool printing_succeeded_ = false; + PrintStatus printing_status_ = PrintStatus::kUnknown; // Indication that the job is getting canceled. bool canceling_job_ = false; diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc @@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode result_code = printing_context_->UseDefaultSettings(); + if (result_code == mojom::ResultCode::kSuccess) + result_code = printing_context_->UpdatePrintSettings(std::move(new_settings)); + InvokeSettingsCallback(std::move(callback), result_code); } - - InvokeSettingsCallback(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) { diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; void PrintForSystemDialog() override; diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644 --- a/components/printing/browser/print_manager.cc +++ b/components/printing/browser/print_manager.cc @@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) { std::move(callback).Run(true); } +void PrintManager::ShowInvalidPrinterSettingsError() {} + void PrintManager::PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) { // Note: Not redundant with cookie checks in the same method in other parts of diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644 --- a/components/printing/browser/print_manager.h +++ b/components/printing/browser/print_manager.h @@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver, DidPrintDocumentCallback callback) override; void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void DidShowPrintDialog() override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index c97825d05cb7d132c9af489998f4ed8c32603c00..fde20b8a6c4811ce728abfee26b2ab7b53027a94 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -296,7 +296,7 @@ union PrintWithParamsResult { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -390,7 +390,10 @@ interface PrintManagerHost { // UI to the user to select the final print settings. If the user cancels or // an error occurs, return null. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled); + + // Tells the browser that there are invalid printer settings. + ShowInvalidPrinterSettingsError(); // Tells the browser printing failed. PrintingFailed(int32 cookie, PrintFailureReason reason); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 5d5144737eace87832ab5c44cd8e2bfdeda5dec2..d9a9b65da336f31f4d302f5363737263d30aea4e 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -45,6 +45,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" @@ -1344,7 +1345,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::Value::Dict() /* new_settings */); if (!weak_this) return; @@ -1375,7 +1377,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1390,7 +1392,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1469,7 +1471,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::Value::Dict()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1520,6 +1523,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2130,7 +2135,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::Value::Dict() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2145,7 +2151,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2153,7 +2161,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2172,8 +2180,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2406,35 +2421,47 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + base::Value::Dict new_settings) { // Reset to default values. ignore_css_margins_ = false; - mojom::PrintPagesParams settings; - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); + mojom::PrintPagesParamsPtr settings; + if (new_settings.empty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + GetPrintManagerHost()->UpdatePrintSettings( + std::move(new_settings), &settings); + } // Check if the printer returned any settings, if the settings are null, // assume there are no printer drivers configured. So safely terminate. - if (!settings.params) { + if (!settings || !settings->params) { // Caller will reset `print_pages_params_`. return false; } - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return true; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + base::Value::Dict settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) { // Browser triggered this code path. It already knows about the failure. notify_browser_of_print_failure_ = false; + GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; } @@ -2538,7 +2565,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 0fea424325081a0ef6720000841ea321b89024d0..c700de4b81fc0c157946e76faedaca6b59aeac0c 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -247,7 +247,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -317,7 +317,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -326,12 +328,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + base::Value::Dict new_settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + base::Value::Dict settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 853c976d87eb2bc571a270bfe2ca5922ed21a6ee..723e937150ce59cf72cc5800ca2af82b0686a534 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn @@ -2905,8 +2905,9 @@ source_set("browser") { "//ppapi/shared_impl", ] - assert(enable_printing) - deps += [ "//printing" ] + if (enable_printing) { + deps += [ "//printing" ] + } if (is_chromeos) { sources += [ diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING) diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644 --- a/sandbox/policy/mac/sandbox_mac.mm +++ b/sandbox/policy/mac/sandbox_mac.mm @@ -41,6 +41,10 @@ #error "This file requires ARC support." #endif +#if BUILDFLAG(ENABLE_PRINTING) +#include "sandbox/policy/mac/print_backend.sb.h" +#endif + namespace sandbox::policy { base::FilePath GetCanonicalPath(const base::FilePath& path) {
closed
electron/electron
https://github.com/electron/electron
38,975
[Bug]: error callback on print
### 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 24.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I have no paper in my printer and when I want print it document stay in queue and electron window.contents.print(options, (success, errorType) => { console.log(success) console.log(errorType) }) errorType is empty and success return true but i am not printed anything because no paper if my document not printing success have to return false and if my document in a queue errorType have to return some information about it ### Actual Behavior success true and no errorType ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/38975
https://github.com/electron/electron/pull/38976
c7bdd907d7e1fdcb7741de02f5ca23d47a436437
117a700724074dfc62649e3e561ff284f07e7cae
2023-07-03T13:55:41Z
c++
2023-07-10T13:26:29Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/BUILD.gn b/BUILD.gn index 08dae2813066a22c16c7cd524fa2c9747bf6ff40..de224c63c242c38b9d12c445a46483a1b2778944 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -971,7 +971,6 @@ if (is_win) { "//media:media_unittests", "//media/midi:midi_unittests", "//net:net_unittests", - "//printing:printing_unittests", "//sql:sql_unittests", "//third_party/breakpad:symupload($host_toolchain)", "//ui/base:ui_base_unittests", @@ -980,6 +979,10 @@ if (is_win) { "//ui/views:views_unittests", "//url:url_unittests", ] + + if (enable_printing) { + deps += [ "//printing:printing_unittests" ] + } } } diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) { auto* rfh = content::RenderFrameHost::FromID(rfh_id); return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query, #if BUILDFLAG(IS_WIN) pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count); - PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) { - use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled); - } + // TODO(codebytere): should we enable this later? + use_skia_ = false; #endif auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings), @@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c976fb2a814e4ff09650982034371e40d1ab77bc..c9115c7bbead588f3099bb194eb293b0e78ad211 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -23,7 +23,9 @@ #include "chrome/browser/bad_message.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" +#if 0 // Electron does not use Chrome error dialogs #include "chrome/browser/printing/print_error_dialog.h" +#endif #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_view_manager_common.h" @@ -83,6 +85,20 @@ namespace printing { namespace { +std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) { + if (status == PrintViewManager::PrintStatus::kInvalid) { + return "Invalid printer settings"; + } else if (status == PrintViewManager::PrintStatus::kCanceled) { + return "Print job canceled"; + } else if (status == PrintViewManager::PrintStatus::kFailed) { + return "Print job failed"; + } + return ""; +} + +using PrintSettingsCallback = + base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; + void OnDidGetDefaultPrintSettings( scoped_refptr<PrintQueriesQueue> queue, bool want_pdf_settings, @@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (printer_query->last_status() != mojom::ResultCode::kSuccess) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings( params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params)) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -122,7 +142,8 @@ void OnDidScriptedPrint( if (printer_query->last_status() != mojom::ResultCode::kSuccess || !printer_query->settings().dpi()) { - std::move(callback).Run(nullptr); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; + std::move(callback).Run(nullptr, canceled); return; } @@ -132,12 +153,12 @@ void OnDidScriptedPrint( params->params.get()); params->params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params->params)) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } params->pages = printer_query->settings().ranges(); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), false); queue->QueuePrinterQuery(std::move(printer_query)); } @@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); + printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -199,12 +222,20 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() { } #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value::Dict settings, + CompletionCallback callback) { if (!StartPrintCommon(rfh)) { return false; } +#if 0 CompletePrintNow(rfh); +#endif + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); return true; } @@ -313,12 +344,13 @@ void PrintViewManagerBase::OnDidUpdatePrintableArea( } PRINTER_LOG(EVENT) << "Paper printable area updated for vendor id " << print_settings->requested_media().vendor_id; - CompleteUpdatePrintSettings(std::move(job_settings), + CompleteUpdatePrintSettings(nullptr /* printer_query */, std::move(job_settings), std::move(print_settings), std::move(callback)); } #endif void PrintViewManagerBase::CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback) { @@ -326,7 +358,8 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( settings->pages = GetPageRangesFromJobSettings(job_settings); settings->params = mojom::PrintParams::New(); RenderParamsFromPrintSettings(*print_settings, settings->params.get()); - settings->params->document_cookie = PrintSettings::NewCookie(); + settings->params->document_cookie = printer_query ? printer_query->cookie() + : PrintSettings::NewCookie(); if (!PrintMsgPrintParamsIsValid(*settings->params)) { mojom::PrinterType printer_type = static_cast<mojom::PrinterType>( *job_settings.FindInt(kSettingPrinterType)); @@ -338,6 +371,10 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( return; } + if (printer_query && printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(std::move(printer_query)); + } + set_cookie(settings->params->document_cookie); std::move(callback).Run(std::move(settings)); } @@ -441,7 +478,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -456,12 +494,15 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + if (params) { set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } else { set_cookie(0); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); } } @@ -598,10 +639,12 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), nullptr); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) @@ -652,10 +695,12 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { std::move(callback).Run(nullptr); return; } +#endif // Printing is always enabled. absl::optional<int> printer_type_value = job_settings.FindInt(kSettingPrinterType); @@ -666,6 +711,7 @@ void PrintViewManagerBase::UpdatePrintSettings( mojom::PrinterType printer_type = static_cast<mojom::PrinterType>(*printer_type_value); +#if 0 // Printing is always enabled. if (printer_type != mojom::PrinterType::kExtension && printer_type != mojom::PrinterType::kPdf && printer_type != mojom::PrinterType::kLocal) { @@ -685,6 +731,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif // Printing is always enabled. std::unique_ptr<PrintSettings> print_settings = PrintSettingsFromJobSettings(job_settings); @@ -704,6 +751,16 @@ void PrintViewManagerBase::UpdatePrintSettings( } } + std::unique_ptr<PrinterQuery> query = + queue_->CreatePrinterQuery(GetCurrentTargetFrame()->GetGlobalId()); + auto* query_ptr = query.get(); + query_ptr->SetSettings( + job_settings.Clone(), + base::BindOnce(&PrintViewManagerBase::CompleteUpdatePrintSettings, + weak_ptr_factory_.GetWeakPtr(), std::move(query), + std::move(job_settings), std::move(print_settings), + std::move(callback))); + #if BUILDFLAG(IS_WIN) // TODO(crbug.com/1424368): Remove this if the printable areas can be made // fully available from `PrintBackend::GetPrinterSemanticCapsAndDefaults()` @@ -726,15 +783,13 @@ void PrintViewManagerBase::UpdatePrintSettings( } #endif - CompleteUpdatePrintSettings(std::move(job_settings), - std::move(print_settings), std::move(callback)); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerBase::IsPrintingEnabled( IsPrintingEnabledCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::move(callback).Run(printing_enabled_.GetValue()); + std::move(callback).Run(true); } void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, @@ -750,14 +805,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !query_with_ui_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #endif @@ -792,6 +847,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); +#if 0 // Electron does not use Chromium error dialogs // `PrintingFailed()` can occur because asynchronous compositing results // don't complete until after a print job has already failed and been // destroyed. In such cases the error notification to the user will @@ -801,7 +857,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, print_job_->document()->cookie() == cookie) { ShowPrintErrorDialogForGenericError(); } - +#endif ReleasePrinterQuery(); } @@ -813,15 +869,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) { test_observers_.RemoveObserver(&observer); } +void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + printing_status_ = PrintStatus::kInvalid; + TerminatePrintJob(true); + } +} + void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf() && !render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) { GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer(); } +#endif } void PrintViewManagerBase::RenderFrameDeleted( @@ -873,7 +938,12 @@ void PrintViewManagerBase::OnJobDone() { // Printing is done, we don't need it anymore. // print_job_->is_job_pending() may still be true, depending on the order // of object registration. - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; + ReleasePrintJob(); +} + +void PrintViewManagerBase::UserInitCanceled() { + printing_status_ = PrintStatus::kCanceled; ReleasePrintJob(); } @@ -882,9 +952,10 @@ void PrintViewManagerBase::OnCanceling() { } void PrintViewManagerBase::OnFailed() { +#if 0 // Electron does not use Chromium error dialogs if (!canceling_job_) ShowPrintErrorDialogForGenericError(); - +#endif TerminatePrintJob(true); } @@ -894,7 +965,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { // Is the document already complete? if (print_job_->document() && print_job_->document()->IsComplete()) { - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; return true; } @@ -942,7 +1013,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current `print_job_`. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -963,7 +1037,7 @@ bool PrintViewManagerBase::CreateNewPrintJob( #endif print_job_->AddObserver(*this); - printing_succeeded_ = false; + printing_status_ = PrintStatus::kFailed; return true; } @@ -1031,6 +1105,11 @@ void PrintViewManagerBase::ReleasePrintJob() { } #endif + if (!callback_.is_null()) { + bool success = printing_status_ == PrintStatus::kSucceeded; + std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_)); + } + if (!print_job_) return; @@ -1038,7 +1117,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // printing_rfh_ should only ever point to a RenderFrameHost with a live // RenderFrame. DCHECK(rfh->IsRenderFrameLive()); - GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); + GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded); } print_job_->RemoveObserver(*this); @@ -1080,7 +1159,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1224,7 +1303,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() { } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict()); for (auto& observer : GetTestObservers()) { observer.OnPrintNow(rfh); @@ -1274,7 +1353,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis( set_analyzing_content(/*analyzing*/ false); if (!allowed || !printing_rfh_ || IsCrashed() || !printing_rfh_->IsRenderFrameLive()) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback)); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 4ae11ba1c9cabb659910271c1ef20ff08a67df67..bbc77212abe5e73b58605058d7a3c49cfa1c003f 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -47,6 +47,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value::Dict settings = {}, + CompletionCallback callback = {}); // Like PrintNow(), but for the node under the context menu, instead of the // entire frame. @@ -136,8 +141,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void ScriptedPrint(mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -145,6 +152,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void AddTestObserver(TestObserver& observer); void RemoveTestObserver(TestObserver& observer); + enum class PrintStatus { + kSucceeded, + kCanceled, + kFailed, + kInvalid, + kUnknown + }; + protected: explicit PrintViewManagerBase(content::WebContents* web_contents); @@ -272,6 +287,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { bool success); #endif void CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback); @@ -301,7 +317,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -371,8 +388,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. - bool printing_succeeded_ = false; + PrintStatus printing_status_ = PrintStatus::kUnknown; // Indication that the job is getting canceled. bool canceling_job_ = false; diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc @@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode result_code = printing_context_->UseDefaultSettings(); + if (result_code == mojom::ResultCode::kSuccess) + result_code = printing_context_->UpdatePrintSettings(std::move(new_settings)); + InvokeSettingsCallback(std::move(callback), result_code); } - - InvokeSettingsCallback(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) { diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; void PrintForSystemDialog() override; diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644 --- a/components/printing/browser/print_manager.cc +++ b/components/printing/browser/print_manager.cc @@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) { std::move(callback).Run(true); } +void PrintManager::ShowInvalidPrinterSettingsError() {} + void PrintManager::PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) { // Note: Not redundant with cookie checks in the same method in other parts of diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644 --- a/components/printing/browser/print_manager.h +++ b/components/printing/browser/print_manager.h @@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver, DidPrintDocumentCallback callback) override; void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void DidShowPrintDialog() override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index c97825d05cb7d132c9af489998f4ed8c32603c00..fde20b8a6c4811ce728abfee26b2ab7b53027a94 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -296,7 +296,7 @@ union PrintWithParamsResult { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -390,7 +390,10 @@ interface PrintManagerHost { // UI to the user to select the final print settings. If the user cancels or // an error occurs, return null. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled); + + // Tells the browser that there are invalid printer settings. + ShowInvalidPrinterSettingsError(); // Tells the browser printing failed. PrintingFailed(int32 cookie, PrintFailureReason reason); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 5d5144737eace87832ab5c44cd8e2bfdeda5dec2..d9a9b65da336f31f4d302f5363737263d30aea4e 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -45,6 +45,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" @@ -1344,7 +1345,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::Value::Dict() /* new_settings */); if (!weak_this) return; @@ -1375,7 +1377,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1390,7 +1392,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1469,7 +1471,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::Value::Dict()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1520,6 +1523,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2130,7 +2135,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::Value::Dict() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2145,7 +2151,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2153,7 +2161,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2172,8 +2180,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2406,35 +2421,47 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + base::Value::Dict new_settings) { // Reset to default values. ignore_css_margins_ = false; - mojom::PrintPagesParams settings; - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); + mojom::PrintPagesParamsPtr settings; + if (new_settings.empty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + GetPrintManagerHost()->UpdatePrintSettings( + std::move(new_settings), &settings); + } // Check if the printer returned any settings, if the settings are null, // assume there are no printer drivers configured. So safely terminate. - if (!settings.params) { + if (!settings || !settings->params) { // Caller will reset `print_pages_params_`. return false; } - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return true; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + base::Value::Dict settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) { // Browser triggered this code path. It already knows about the failure. notify_browser_of_print_failure_ = false; + GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; } @@ -2538,7 +2565,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 0fea424325081a0ef6720000841ea321b89024d0..c700de4b81fc0c157946e76faedaca6b59aeac0c 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -247,7 +247,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -317,7 +317,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -326,12 +328,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + base::Value::Dict new_settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + base::Value::Dict settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 853c976d87eb2bc571a270bfe2ca5922ed21a6ee..723e937150ce59cf72cc5800ca2af82b0686a534 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn @@ -2905,8 +2905,9 @@ source_set("browser") { "//ppapi/shared_impl", ] - assert(enable_printing) - deps += [ "//printing" ] + if (enable_printing) { + deps += [ "//printing" ] + } if (is_chromeos) { sources += [ diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING) diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644 --- a/sandbox/policy/mac/sandbox_mac.mm +++ b/sandbox/policy/mac/sandbox_mac.mm @@ -41,6 +41,10 @@ #error "This file requires ARC support." #endif +#if BUILDFLAG(ENABLE_PRINTING) +#include "sandbox/policy/mac/print_backend.sb.h" +#endif + namespace sandbox::policy { base::FilePath GetCanonicalPath(const base::FilePath& path) {
closed
electron/electron
https://github.com/electron/electron
38,944
[Bug]: print() crashes on Windows, but works on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior webContents.print() should work and print page:) ### Actual Behavior in doesnt. When I call print(), app crashes silently. I can't catch any logs, even with process uncaughtException/unhandledRejection events. ### Testcase Gist URL _No response_ ### Additional Information I have created new empty project to test this bug. I have empty project with only one window. I just load image to the window and try to print it. ``` const createWindow = () => { const mainWindow = new BrowserWindow({ width: 800, height: 600, }); mainWindow.loadURL( "https://www.kasandbox.org/programming-images/avatars/leaf-blue.png" ); mainWindow.webContents.openDevTools(); mainWindow.webContents.on("did-finish-load", () => { console.log("did-finish-load"); mainWindow.webContents.print({ // silent: true, // deviceName: "Xprinter XP-365B", }); }); }; ``` I have tested it in different environments and different electron version (including latest ^26.0.0-beta.1). I works on macOS and always crashes on Windows (I've tried different versions: win 10, win 11, parallels, etc). Can you give me an advice, how it can be fixed?
https://github.com/electron/electron/issues/38944
https://github.com/electron/electron/pull/38976
c7bdd907d7e1fdcb7741de02f5ca23d47a436437
117a700724074dfc62649e3e561ff284f07e7cae
2023-06-28T23:10:46Z
c++
2023-07-10T13:26:29Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/BUILD.gn b/BUILD.gn index 08dae2813066a22c16c7cd524fa2c9747bf6ff40..de224c63c242c38b9d12c445a46483a1b2778944 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -971,7 +971,6 @@ if (is_win) { "//media:media_unittests", "//media/midi:midi_unittests", "//net:net_unittests", - "//printing:printing_unittests", "//sql:sql_unittests", "//third_party/breakpad:symupload($host_toolchain)", "//ui/base:ui_base_unittests", @@ -980,6 +979,10 @@ if (is_win) { "//ui/views:views_unittests", "//url:url_unittests", ] + + if (enable_printing) { + deps += [ "//printing:printing_unittests" ] + } } } diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) { auto* rfh = content::RenderFrameHost::FromID(rfh_id); return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } +#endif #endif // BUILDFLAG(IS_WIN) @@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query, #if BUILDFLAG(IS_WIN) pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count); - PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) { - use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled); - } + // TODO(codebytere): should we enable this later? + use_skia_ = false; #endif auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings), @@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_)); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c976fb2a814e4ff09650982034371e40d1ab77bc..c9115c7bbead588f3099bb194eb293b0e78ad211 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -23,7 +23,9 @@ #include "chrome/browser/bad_message.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" +#if 0 // Electron does not use Chrome error dialogs #include "chrome/browser/printing/print_error_dialog.h" +#endif #include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_view_manager_common.h" @@ -83,6 +85,20 @@ namespace printing { namespace { +std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) { + if (status == PrintViewManager::PrintStatus::kInvalid) { + return "Invalid printer settings"; + } else if (status == PrintViewManager::PrintStatus::kCanceled) { + return "Print job canceled"; + } else if (status == PrintViewManager::PrintStatus::kFailed) { + return "Print job failed"; + } + return ""; +} + +using PrintSettingsCallback = + base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>; + void OnDidGetDefaultPrintSettings( scoped_refptr<PrintQueriesQueue> queue, bool want_pdf_settings, @@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings( DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (printer_query->last_status() != mojom::ResultCode::kSuccess) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings( params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params)) { +#if 0 // Electron does not use Chrome error dialogs if (!want_pdf_settings) { ShowPrintErrorDialogForInvalidPrinterError(); } +#endif std::move(callback).Run(nullptr); return; } @@ -122,7 +142,8 @@ void OnDidScriptedPrint( if (printer_query->last_status() != mojom::ResultCode::kSuccess || !printer_query->settings().dpi()) { - std::move(callback).Run(nullptr); + bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled; + std::move(callback).Run(nullptr, canceled); return; } @@ -132,12 +153,12 @@ void OnDidScriptedPrint( params->params.get()); params->params->document_cookie = printer_query->cookie(); if (!PrintMsgPrintParamsIsValid(*params->params)) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } params->pages = printer_query->settings().ranges(); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), false); queue->QueuePrinterQuery(std::move(printer_query)); } @@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); - printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); + printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -199,12 +222,20 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() { } #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value::Dict settings, + CompletionCallback callback) { if (!StartPrintCommon(rfh)) { return false; } +#if 0 CompletePrintNow(rfh); +#endif + callback_ = std::move(callback); + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); return true; } @@ -313,12 +344,13 @@ void PrintViewManagerBase::OnDidUpdatePrintableArea( } PRINTER_LOG(EVENT) << "Paper printable area updated for vendor id " << print_settings->requested_media().vendor_id; - CompleteUpdatePrintSettings(std::move(job_settings), + CompleteUpdatePrintSettings(nullptr /* printer_query */, std::move(job_settings), std::move(print_settings), std::move(callback)); } #endif void PrintViewManagerBase::CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback) { @@ -326,7 +358,8 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( settings->pages = GetPageRangesFromJobSettings(job_settings); settings->params = mojom::PrintParams::New(); RenderParamsFromPrintSettings(*print_settings, settings->params.get()); - settings->params->document_cookie = PrintSettings::NewCookie(); + settings->params->document_cookie = printer_query ? printer_query->cookie() + : PrintSettings::NewCookie(); if (!PrintMsgPrintParamsIsValid(*settings->params)) { mojom::PrinterType printer_type = static_cast<mojom::PrinterType>( *job_settings.FindInt(kSettingPrinterType)); @@ -338,6 +371,10 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings( return; } + if (printer_query && printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(std::move(printer_query)); + } + set_cookie(settings->params->document_cookie); std::move(callback).Run(std::move(settings)); } @@ -441,7 +478,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply( void PrintViewManagerBase::ScriptedPrintReply( ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params) { + mojom::PrintPagesParamsPtr params, + bool canceled) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); #if BUILDFLAG(ENABLE_OOP_PRINTING) @@ -456,12 +494,15 @@ void PrintViewManagerBase::ScriptedPrintReply( return; } + if (canceled) + UserInitCanceled(); + if (params) { set_cookie(params->params->document_cookie); - std::move(callback).Run(std::move(params)); + std::move(callback).Run(std::move(params), canceled); } else { set_cookie(0); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); } } @@ -598,10 +639,12 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), nullptr); return; } +#endif #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && #if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS) @@ -652,10 +695,12 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { std::move(callback).Run(nullptr); return; } +#endif // Printing is always enabled. absl::optional<int> printer_type_value = job_settings.FindInt(kSettingPrinterType); @@ -666,6 +711,7 @@ void PrintViewManagerBase::UpdatePrintSettings( mojom::PrinterType printer_type = static_cast<mojom::PrinterType>(*printer_type_value); +#if 0 // Printing is always enabled. if (printer_type != mojom::PrinterType::kExtension && printer_type != mojom::PrinterType::kPdf && printer_type != mojom::PrinterType::kLocal) { @@ -685,6 +731,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.Set(kSettingRasterizePdfDpi, value); } +#endif // Printing is always enabled. std::unique_ptr<PrintSettings> print_settings = PrintSettingsFromJobSettings(job_settings); @@ -704,6 +751,16 @@ void PrintViewManagerBase::UpdatePrintSettings( } } + std::unique_ptr<PrinterQuery> query = + queue_->CreatePrinterQuery(GetCurrentTargetFrame()->GetGlobalId()); + auto* query_ptr = query.get(); + query_ptr->SetSettings( + job_settings.Clone(), + base::BindOnce(&PrintViewManagerBase::CompleteUpdatePrintSettings, + weak_ptr_factory_.GetWeakPtr(), std::move(query), + std::move(job_settings), std::move(print_settings), + std::move(callback))); + #if BUILDFLAG(IS_WIN) // TODO(crbug.com/1424368): Remove this if the printable areas can be made // fully available from `PrintBackend::GetPrinterSemanticCapsAndDefaults()` @@ -726,15 +783,13 @@ void PrintViewManagerBase::UpdatePrintSettings( } #endif - CompleteUpdatePrintSettings(std::move(job_settings), - std::move(print_settings), std::move(callback)); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerBase::IsPrintingEnabled( IsPrintingEnabledCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - std::move(callback).Run(printing_enabled_.GetValue()); + std::move(callback).Run(true); } void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, @@ -750,14 +805,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params, // didn't happen for some reason. bad_message::ReceivedBadMessage( render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME); - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #if BUILDFLAG(ENABLE_OOP_PRINTING) if (printing::features::kEnableOopPrintDriversJobPrint.Get() && !query_with_ui_client_id_.has_value()) { // Renderer process has requested settings outside of the expected setup. - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } #endif @@ -792,6 +847,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, PrintManager::PrintingFailed(cookie, reason); +#if 0 // Electron does not use Chromium error dialogs // `PrintingFailed()` can occur because asynchronous compositing results // don't complete until after a print job has already failed and been // destroyed. In such cases the error notification to the user will @@ -801,7 +857,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie, print_job_->document()->cookie() == cookie) { ShowPrintErrorDialogForGenericError(); } - +#endif ReleasePrinterQuery(); } @@ -813,15 +869,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) { test_observers_.RemoveObserver(&observer); } +void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + printing_status_ = PrintStatus::kInvalid; + TerminatePrintJob(true); + } +} + void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 if (new_state == content::RenderFrameHost::LifecycleState::kActive && render_frame_host->GetProcess()->IsPdf() && !render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) { GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer(); } +#endif } void PrintViewManagerBase::RenderFrameDeleted( @@ -873,7 +938,12 @@ void PrintViewManagerBase::OnJobDone() { // Printing is done, we don't need it anymore. // print_job_->is_job_pending() may still be true, depending on the order // of object registration. - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; + ReleasePrintJob(); +} + +void PrintViewManagerBase::UserInitCanceled() { + printing_status_ = PrintStatus::kCanceled; ReleasePrintJob(); } @@ -882,9 +952,10 @@ void PrintViewManagerBase::OnCanceling() { } void PrintViewManagerBase::OnFailed() { +#if 0 // Electron does not use Chromium error dialogs if (!canceling_job_) ShowPrintErrorDialogForGenericError(); - +#endif TerminatePrintJob(true); } @@ -894,7 +965,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() { // Is the document already complete? if (print_job_->document() && print_job_->document()->IsComplete()) { - printing_succeeded_ = true; + printing_status_ = PrintStatus::kSucceeded; return true; } @@ -942,7 +1013,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current `print_job_`. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -963,7 +1037,7 @@ bool PrintViewManagerBase::CreateNewPrintJob( #endif print_job_->AddObserver(*this); - printing_succeeded_ = false; + printing_status_ = PrintStatus::kFailed; return true; } @@ -1031,6 +1105,11 @@ void PrintViewManagerBase::ReleasePrintJob() { } #endif + if (!callback_.is_null()) { + bool success = printing_status_ == PrintStatus::kSucceeded; + std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_)); + } + if (!print_job_) return; @@ -1038,7 +1117,7 @@ void PrintViewManagerBase::ReleasePrintJob() { // printing_rfh_ should only ever point to a RenderFrameHost with a live // RenderFrame. DCHECK(rfh->IsRenderFrameLive()); - GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); + GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded); } print_job_->RemoveObserver(*this); @@ -1080,7 +1159,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { @@ -1224,7 +1303,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() { } void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) { - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict()); for (auto& observer : GetTestObservers()) { observer.OnPrintNow(rfh); @@ -1274,7 +1353,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis( set_analyzing_content(/*analyzing*/ false); if (!allowed || !printing_rfh_ || IsCrashed() || !printing_rfh_->IsRenderFrameLive()) { - std::move(callback).Run(nullptr); + std::move(callback).Run(nullptr, false); return; } CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback)); diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 4ae11ba1c9cabb659910271c1ef20ff08a67df67..bbc77212abe5e73b58605058d7a3c49cfa1c003f 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -47,6 +47,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent = true, + base::Value::Dict settings = {}, + CompletionCallback callback = {}); // Like PrintNow(), but for the node under the context menu, instead of the // entire frame. @@ -136,8 +141,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void ScriptedPrint(mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; + void UserInitCanceled(); // Adds and removes observers for `PrintViewManagerBase` events. The order in // which notifications are sent to observers is undefined. Observers must be @@ -145,6 +152,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { void AddTestObserver(TestObserver& observer); void RemoveTestObserver(TestObserver& observer); + enum class PrintStatus { + kSucceeded, + kCanceled, + kFailed, + kInvalid, + kUnknown + }; + protected: explicit PrintViewManagerBase(content::WebContents* web_contents); @@ -272,6 +287,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { bool success); #endif void CompleteUpdatePrintSettings( + std::unique_ptr<PrinterQuery> printer_query, base::Value::Dict job_settings, std::unique_ptr<PrintSettings> print_settings, UpdatePrintSettingsCallback callback); @@ -301,7 +317,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Runs `callback` with `params` to reply to ScriptedPrint(). void ScriptedPrintReply(ScriptedPrintCallback callback, int process_id, - mojom::PrintPagesParamsPtr params); + mojom::PrintPagesParamsPtr params, + bool canceled); // Requests the RenderView to render all the missing pages for the print job. // No-op if no print job is pending. Returns true if at least one page has @@ -371,8 +388,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. - bool printing_succeeded_ = false; + PrintStatus printing_status_ = PrintStatus::kUnknown; // Indication that the job is getting canceled. bool canceling_job_ = false; diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc @@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings, #endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS) } - mojom::ResultCode result; { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode result_code = printing_context_->UseDefaultSettings(); + if (result_code == mojom::ResultCode::kSuccess) + result_code = printing_context_->UpdatePrintSettings(std::move(new_settings)); + InvokeSettingsCallback(std::move(callback), result_code); } - - InvokeSettingsCallback(std::move(callback), result); } #if BUILDFLAG(IS_CHROMEOS) diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc @@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame( FakePrintRenderFrame::~FakePrintRenderFrame() = default; -void FakePrintRenderFrame::PrintRequestedPages() {} +void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {} void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) { diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644 --- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h +++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h @@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame { private: // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; void PrintForSystemDialog() override; diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644 --- a/components/printing/browser/print_manager.cc +++ b/components/printing/browser/print_manager.cc @@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) { std::move(callback).Run(true); } +void PrintManager::ShowInvalidPrinterSettingsError() {} + void PrintManager::PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) { // Note: Not redundant with cookie checks in the same method in other parts of diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644 --- a/components/printing/browser/print_manager.h +++ b/components/printing/browser/print_manager.h @@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver, DidPrintDocumentCallback callback) override; void IsPrintingEnabled(IsPrintingEnabledCallback callback) override; void DidShowPrintDialog() override; + void ShowInvalidPrinterSettingsError() override; void PrintingFailed(int32_t cookie, mojom::PrintFailureReason reason) override; diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index c97825d05cb7d132c9af489998f4ed8c32603c00..fde20b8a6c4811ce728abfee26b2ab7b53027a94 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -296,7 +296,7 @@ union PrintWithParamsResult { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Requests the frame to be printed with specified parameters. This is used // to programmatically produce PDF by request from the browser (e.g. over @@ -390,7 +390,10 @@ interface PrintManagerHost { // UI to the user to select the final print settings. If the user cancels or // an error occurs, return null. [Sync] - ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings); + ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled); + + // Tells the browser that there are invalid printer settings. + ShowInvalidPrinterSettingsError(); // Tells the browser printing failed. PrintingFailed(int32 cookie, PrintFailureReason reason); diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 5d5144737eace87832ab5c44cd8e2bfdeda5dec2..d9a9b65da336f31f4d302f5363737263d30aea4e 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -45,6 +45,7 @@ #include "printing/mojom/print.mojom.h" #include "printing/page_number.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" @@ -1344,7 +1345,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::Value::Dict() /* new_settings */); if (!weak_this) return; @@ -1375,7 +1377,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1390,7 +1392,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1469,7 +1471,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::Value::Dict()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1520,6 +1523,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -2130,7 +2135,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::Value::Dict() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -2145,7 +2151,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -2153,7 +2161,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -2172,8 +2180,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2406,35 +2421,47 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + base::Value::Dict new_settings) { // Reset to default values. ignore_css_margins_ = false; - mojom::PrintPagesParams settings; - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); + mojom::PrintPagesParamsPtr settings; + if (new_settings.empty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + GetPrintManagerHost()->UpdatePrintSettings( + std::move(new_settings), &settings); + } // Check if the printer returned any settings, if the settings are null, // assume there are no printer drivers configured. So safely terminate. - if (!settings.params) { + if (!settings || !settings->params) { // Caller will reset `print_pages_params_`. return false; } - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return true; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + base::Value::Dict settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) { // Browser triggered this code path. It already knows about the failure. notify_browser_of_print_failure_ = false; + GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; } @@ -2538,7 +2565,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser( std::move(params), base::BindOnce( [](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output, - mojom::PrintPagesParamsPtr input) { + mojom::PrintPagesParamsPtr input, bool canceled) { *output = std::move(input); std::move(quit_closure).Run(); }, diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 0fea424325081a0ef6720000841ea321b89024d0..c700de4b81fc0c157946e76faedaca6b59aeac0c 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -247,7 +247,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value::Dict settings) override; void PrintWithParams(mojom::PrintPagesParamsPtr params, PrintWithParamsCallback callback) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -317,7 +317,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value::Dict settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -326,12 +328,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + base::Value::Dict new_settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + base::Value::Dict settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 853c976d87eb2bc571a270bfe2ca5922ed21a6ee..723e937150ce59cf72cc5800ca2af82b0686a534 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn @@ -2905,8 +2905,9 @@ source_set("browser") { "//ppapi/shared_impl", ] - assert(enable_printing) - deps += [ "//printing" ] + if (enable_printing) { + deps += [ "//printing" ] + } if (is_chromeos) { sources += [ diff --git a/printing/printing_context.cc b/printing/printing_context.cc index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value::Dict job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { bool PrintingAborted() const { return abort_printing_; } + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING) diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644 --- a/sandbox/policy/mac/sandbox_mac.mm +++ b/sandbox/policy/mac/sandbox_mac.mm @@ -41,6 +41,10 @@ #error "This file requires ARC support." #endif +#if BUILDFLAG(ENABLE_PRINTING) +#include "sandbox/policy/mac/print_backend.sb.h" +#endif + namespace sandbox::policy { base::FilePath GetCanonicalPath(const base::FilePath& path) {
closed
electron/electron
https://github.com/electron/electron
38,786
wayland csd on gnome are broke for 25.x and newer.
### 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 25.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux / 6.3.7-zen1-1-zen ### What arch are you using? x64 ### Last Known Working Electron version 24.5 ### Expected Behavior `$ electron24 --ozone-platform-hint=auto --enable-features=UseOzonePlatform,WaylandWindowDecorations` ![Zrzut ekranu z 2023-06-14 15-12-55](https://github.com/electron/electron/assets/22305379/6261fe32-040a-4f9b-8e20-601fc4daf2f2) ### Actual Behavior `$ electron25 --ozone-platform-hint=auto --enable-features=UseOzonePlatform,WaylandWindowDecorations` ![Zrzut ekranu z 2023-06-14 15-14-58](https://github.com/electron/electron/assets/22305379/44b87b93-f081-416d-83c1-6d89bde184d1) ### Testcase Gist URL _No response_ ### Additional Information any electron version newer than 24 (25/alpha-26/nightbuild-27) are broken
https://github.com/electron/electron/issues/38786
https://github.com/electron/electron/pull/39003
f3f3f5390423207bd2d26e398a565bf2f13dc759
3e3152008ff569632e0b36d53ac9a24fae515709
2023-06-14T13:19:56Z
c++
2023-07-10T20:52:12Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_( ui::LinuxUiTheme::GetForProfile(nullptr)->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (auto* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (auto* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(GetTitlebarBounds().height(), 0, 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive(), tiled_edges()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } views::View* ClientFrameViewLinux::TargetForRect(views::View* root, const gfx::Rect& rect) { return views::NonClientFrameView::TargetForRect(root, rect); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
38,786
wayland csd on gnome are broke for 25.x and newer.
### 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 25.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux / 6.3.7-zen1-1-zen ### What arch are you using? x64 ### Last Known Working Electron version 24.5 ### Expected Behavior `$ electron24 --ozone-platform-hint=auto --enable-features=UseOzonePlatform,WaylandWindowDecorations` ![Zrzut ekranu z 2023-06-14 15-12-55](https://github.com/electron/electron/assets/22305379/6261fe32-040a-4f9b-8e20-601fc4daf2f2) ### Actual Behavior `$ electron25 --ozone-platform-hint=auto --enable-features=UseOzonePlatform,WaylandWindowDecorations` ![Zrzut ekranu z 2023-06-14 15-14-58](https://github.com/electron/electron/assets/22305379/44b87b93-f081-416d-83c1-6d89bde184d1) ### Testcase Gist URL _No response_ ### Additional Information any electron version newer than 24 (25/alpha-26/nightbuild-27) are broken
https://github.com/electron/electron/issues/38786
https://github.com/electron/electron/pull/39003
f3f3f5390423207bd2d26e398a565bf2f13dc759
3e3152008ff569632e0b36d53ac9a24fae515709
2023-06-14T13:19:56Z
c++
2023-07-10T20:52:12Z
shell/browser/ui/views/client_frame_view_linux.cc
// Copyright (c) 2021 Ryan Gonzalez. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/views/client_frame_view_linux.h" #include <algorithm> #include "base/strings/utf_string_conversions.h" #include "cc/paint/paint_filter.h" #include "cc/paint/paint_flags.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "ui/base/hit_test.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_list.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/text_constants.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/nav_button_provider.h" #include "ui/native_theme/native_theme.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/style/typography.h" #include "ui/views/widget/widget.h" #include "ui/views/window/frame_buttons.h" #include "ui/views/window/window_button_order_provider.h" namespace electron { namespace { // These values should be the same as Chromium uses. constexpr int kResizeOutsideBorderSize = 10; constexpr int kResizeInsideBoundsSize = 5; ui::NavButtonProvider::ButtonState ButtonStateToNavButtonProviderState( views::Button::ButtonState state) { switch (state) { case views::Button::STATE_NORMAL: return ui::NavButtonProvider::ButtonState::kNormal; case views::Button::STATE_HOVERED: return ui::NavButtonProvider::ButtonState::kHovered; case views::Button::STATE_PRESSED: return ui::NavButtonProvider::ButtonState::kPressed; case views::Button::STATE_DISABLED: return ui::NavButtonProvider::ButtonState::kDisabled; case views::Button::STATE_COUNT: default: NOTREACHED(); return ui::NavButtonProvider::ButtonState::kNormal; } } } // namespace // static const char ClientFrameViewLinux::kViewClassName[] = "ClientFrameView"; ClientFrameViewLinux::ClientFrameViewLinux() : theme_(ui::NativeTheme::GetInstanceForNativeUi()), nav_button_provider_( ui::LinuxUiTheme::GetForProfile(nullptr)->CreateNavButtonProvider()), nav_buttons_{ NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kClose, views::FrameButton::kClose, &views::Widget::Close, IDS_APP_ACCNAME_CLOSE, HTCLOSE}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMaximize, views::FrameButton::kMaximize, &views::Widget::Maximize, IDS_APP_ACCNAME_MAXIMIZE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kRestore, views::FrameButton::kMaximize, &views::Widget::Restore, IDS_APP_ACCNAME_RESTORE, HTMAXBUTTON}, NavButton{ui::NavButtonProvider::FrameButtonDisplayType::kMinimize, views::FrameButton::kMinimize, &views::Widget::Minimize, IDS_APP_ACCNAME_MINIMIZE, HTMINBUTTON}, }, trailing_frame_buttons_{views::FrameButton::kMinimize, views::FrameButton::kMaximize, views::FrameButton::kClose} { for (auto& button : nav_buttons_) { button.button = new views::ImageButton(); button.button->SetImageVerticalAlignment(views::ImageButton::ALIGN_MIDDLE); button.button->SetAccessibleName( l10n_util::GetStringUTF16(button.accessibility_id)); AddChildView(button.button); } title_ = new views::Label(); title_->SetSubpixelRenderingEnabled(false); title_->SetAutoColorReadabilityEnabled(false); title_->SetHorizontalAlignment(gfx::ALIGN_CENTER); title_->SetVerticalAlignment(gfx::ALIGN_MIDDLE); title_->SetTextStyle(views::style::STYLE_TAB_ACTIVE); AddChildView(title_); native_theme_observer_.Observe(theme_); if (auto* ui = ui::LinuxUi::instance()) { ui->AddWindowButtonOrderObserver(this); OnWindowButtonOrderingChange(); } } ClientFrameViewLinux::~ClientFrameViewLinux() { if (auto* ui = ui::LinuxUi::instance()) ui->RemoveWindowButtonOrderObserver(this); theme_->RemoveObserver(this); } void ClientFrameViewLinux::Init(NativeWindowViews* window, views::Widget* frame) { FramelessView::Init(window, frame); // Unretained() is safe because the subscription is saved into an instance // member and thus will be cancelled upon the instance's destruction. paint_as_active_changed_subscription_ = frame_->RegisterPaintAsActiveChangedCallback(base::BindRepeating( &ClientFrameViewLinux::PaintAsActiveChanged, base::Unretained(this))); auto* tree_host = static_cast<ElectronDesktopWindowTreeHostLinux*>( ElectronDesktopWindowTreeHostLinux::GetHostForWidget( window->GetAcceleratedWidget())); host_supports_client_frame_shadow_ = tree_host->SupportsClientFrameShadow(); frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateWindowTitle(); for (auto& button : nav_buttons_) { // Unretained() is safe because the buttons are added as children to, and // thus owned by, this view. Thus, the buttons themselves will be destroyed // when this view is destroyed, and the frame's life must never outlive the // view. button.button->SetCallback( base::BindRepeating(button.callback, base::Unretained(frame))); } UpdateThemeValues(); } gfx::Insets ClientFrameViewLinux::GetBorderDecorationInsets() const { return frame_provider_->GetFrameThicknessDip(); } gfx::Insets ClientFrameViewLinux::GetInputInsets() const { return gfx::Insets( host_supports_client_frame_shadow_ ? -kResizeOutsideBorderSize : 0); } gfx::Rect ClientFrameViewLinux::GetWindowContentBounds() const { gfx::Rect content_bounds = bounds(); content_bounds.Inset(GetBorderDecorationInsets()); return content_bounds; } SkRRect ClientFrameViewLinux::GetRoundedWindowContentBounds() const { SkRect rect = gfx::RectToSkRect(GetWindowContentBounds()); SkRRect rrect; if (!frame_->IsMaximized()) { SkPoint round_point{theme_values_.window_border_radius, theme_values_.window_border_radius}; SkPoint radii[] = {round_point, round_point, {}, {}}; rrect.setRectRadii(rect, radii); } else { rrect.setRect(rect); } return rrect; } void ClientFrameViewLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateThemeValues(); } void ClientFrameViewLinux::OnWindowButtonOrderingChange() { auto* provider = views::WindowButtonOrderProvider::GetInstance(); leading_frame_buttons_ = provider->leading_buttons(); trailing_frame_buttons_ = provider->trailing_buttons(); InvalidateLayout(); } int ClientFrameViewLinux::ResizingBorderHitTest(const gfx::Point& point) { return ResizingBorderHitTestImpl( point, GetBorderDecorationInsets() + gfx::Insets(kResizeInsideBoundsSize)); } gfx::Rect ClientFrameViewLinux::GetBoundsForClientView() const { gfx::Rect client_bounds = bounds(); if (!frame_->IsFullscreen()) { client_bounds.Inset(GetBorderDecorationInsets()); client_bounds.Inset( gfx::Insets::TLBR(GetTitlebarBounds().height(), 0, 0, 0)); } return client_bounds; } gfx::Rect ClientFrameViewLinux::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { gfx::Insets insets = bounds().InsetsFrom(GetBoundsForClientView()); return gfx::Rect(std::max(0, client_bounds.x() - insets.left()), std::max(0, client_bounds.y() - insets.top()), client_bounds.width() + insets.width(), client_bounds.height() + insets.height()); } int ClientFrameViewLinux::NonClientHitTest(const gfx::Point& point) { int component = ResizingBorderHitTest(point); if (component != HTNOWHERE) { return component; } for (auto& button : nav_buttons_) { if (button.button->GetVisible() && button.button->GetMirroredBounds().Contains(point)) { return button.hit_test_id; } } if (GetTitlebarBounds().Contains(point)) { return HTCAPTION; } return FramelessView::NonClientHitTest(point); } void ClientFrameViewLinux::GetWindowMask(const gfx::Size& size, SkPath* window_mask) { // Nothing to do here, as transparency is used for decorations, not masks. } void ClientFrameViewLinux::UpdateWindowTitle() { title_->SetText(base::UTF8ToUTF16(window_->GetTitle())); } void ClientFrameViewLinux::SizeConstraintsChanged() { InvalidateLayout(); } gfx::Size ClientFrameViewLinux::CalculatePreferredSize() const { return SizeWithDecorations(FramelessView::CalculatePreferredSize()); } gfx::Size ClientFrameViewLinux::GetMinimumSize() const { return SizeWithDecorations(FramelessView::GetMinimumSize()); } gfx::Size ClientFrameViewLinux::GetMaximumSize() const { return SizeWithDecorations(FramelessView::GetMaximumSize()); } void ClientFrameViewLinux::Layout() { FramelessView::Layout(); if (frame_->IsFullscreen()) { // Just hide everything and return. for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } title_->SetVisible(false); return; } frame_provider_ = ui::LinuxUiTheme::GetForProfile(nullptr)->GetWindowFrameProvider( !host_supports_client_frame_shadow_, frame_->IsMaximized()); UpdateButtonImages(); LayoutButtons(); gfx::Rect title_bounds(GetTitlebarContentBounds()); title_bounds.Inset(theme_values_.title_padding); title_->SetVisible(true); title_->SetBounds(title_bounds.x(), title_bounds.y(), title_bounds.width(), title_bounds.height()); } void ClientFrameViewLinux::OnPaint(gfx::Canvas* canvas) { if (!frame_->IsFullscreen()) { frame_provider_->PaintWindowFrame(canvas, GetLocalBounds(), GetTitlebarBounds().bottom(), ShouldPaintAsActive(), tiled_edges()); } } const char* ClientFrameViewLinux::GetClassName() const { return kViewClassName; } void ClientFrameViewLinux::PaintAsActiveChanged() { UpdateThemeValues(); } void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkLabel#label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( headerbar_context, "GtkButton#button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context); gtk_style_context_set_parent(button_context, headerbar_context); // ShouldPaintAsActive asks the widget, so assume active if the widget is not // set yet. if (GetWidget() != nullptr && !ShouldPaintAsActive()) { gtk_style_context_set_state(window_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(headerbar_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(title_context, GTK_STATE_FLAG_BACKDROP); gtk_style_context_set_state(button_context, GTK_STATE_FLAG_BACKDROP); } theme_values_.window_border_radius = frame_provider_->GetTopCornerRadiusDip(); gtk::GtkStyleContextGet(headerbar_context, "min-height", &theme_values_.titlebar_min_height, nullptr); theme_values_.titlebar_padding = gtk::GtkStyleContextGetPadding(headerbar_context); theme_values_.title_color = gtk::GtkStyleContextGetColor(title_context); theme_values_.title_padding = gtk::GtkStyleContextGetPadding(title_context); gtk::GtkStyleContextGet(button_context, "min-height", &theme_values_.button_min_size, nullptr); theme_values_.button_padding = gtk::GtkStyleContextGetPadding(button_context); title_->SetEnabledColor(theme_values_.title_color); InvalidateLayout(); SchedulePaint(); } ui::NavButtonProvider::FrameButtonDisplayType ClientFrameViewLinux::GetButtonTypeToSkip() const { return frame_->IsMaximized() ? ui::NavButtonProvider::FrameButtonDisplayType::kMaximize : ui::NavButtonProvider::FrameButtonDisplayType::kRestore; } void ClientFrameViewLinux::UpdateButtonImages() { nav_button_provider_->RedrawImages(theme_values_.button_min_size, frame_->IsMaximized(), ShouldPaintAsActive()); ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); for (NavButton& button : nav_buttons_) { if (button.type == skip_type) { continue; } for (size_t state_id = 0; state_id < views::Button::STATE_COUNT; state_id++) { views::Button::ButtonState state = static_cast<views::Button::ButtonState>(state_id); button.button->SetImage( state, nav_button_provider_->GetImage( button.type, ButtonStateToNavButtonProviderState(state))); } } } void ClientFrameViewLinux::LayoutButtons() { for (NavButton& button : nav_buttons_) { button.button->SetVisible(false); } gfx::Rect remaining_content_bounds = GetTitlebarContentBounds(); LayoutButtonsOnSide(ButtonSide::kLeading, &remaining_content_bounds); LayoutButtonsOnSide(ButtonSide::kTrailing, &remaining_content_bounds); } void ClientFrameViewLinux::LayoutButtonsOnSide( ButtonSide side, gfx::Rect* remaining_content_bounds) { ui::NavButtonProvider::FrameButtonDisplayType skip_type = GetButtonTypeToSkip(); std::vector<views::FrameButton> frame_buttons; switch (side) { case ButtonSide::kLeading: frame_buttons = leading_frame_buttons_; break; case ButtonSide::kTrailing: frame_buttons = trailing_frame_buttons_; // We always lay buttons out going from the edge towards the center, but // they are given to us as left-to-right, so reverse them. std::reverse(frame_buttons.begin(), frame_buttons.end()); break; default: NOTREACHED(); } for (views::FrameButton frame_button : frame_buttons) { auto* button = std::find_if( nav_buttons_.begin(), nav_buttons_.end(), [&](const NavButton& test) { return test.type != skip_type && test.frame_button == frame_button; }); CHECK(button != nav_buttons_.end()) << "Failed to find frame button: " << static_cast<int>(frame_button); if (button->type == skip_type) { continue; } button->button->SetVisible(true); int button_width = theme_values_.button_min_size; int next_button_offset = button_width + nav_button_provider_->GetInterNavButtonSpacing(); int x_position = 0; gfx::Insets inset_after_placement; switch (side) { case ButtonSide::kLeading: x_position = remaining_content_bounds->x(); inset_after_placement.set_left(next_button_offset); break; case ButtonSide::kTrailing: x_position = remaining_content_bounds->right() - button_width; inset_after_placement.set_right(next_button_offset); break; default: NOTREACHED(); } button->button->SetBounds(x_position, remaining_content_bounds->y(), button_width, remaining_content_bounds->height()); remaining_content_bounds->Inset(inset_after_placement); } } gfx::Rect ClientFrameViewLinux::GetTitlebarBounds() const { if (frame_->IsFullscreen()) { return gfx::Rect(); } int font_height = gfx::FontList().GetHeight(); int titlebar_height = std::max(font_height, theme_values_.titlebar_min_height) + GetTitlebarContentInsets().height(); gfx::Insets decoration_insets = GetBorderDecorationInsets(); // We add the inset height here, so the .Inset() that follows won't reduce it // to be too small. gfx::Rect titlebar(width(), titlebar_height + decoration_insets.height()); titlebar.Inset(decoration_insets); return titlebar; } gfx::Insets ClientFrameViewLinux::GetTitlebarContentInsets() const { return theme_values_.titlebar_padding + nav_button_provider_->GetTopAreaSpacing(); } gfx::Rect ClientFrameViewLinux::GetTitlebarContentBounds() const { gfx::Rect titlebar(GetTitlebarBounds()); titlebar.Inset(GetTitlebarContentInsets()); return titlebar; } gfx::Size ClientFrameViewLinux::SizeWithDecorations(gfx::Size size) const { gfx::Insets decoration_insets = GetBorderDecorationInsets(); size.Enlarge(0, GetTitlebarBounds().height()); size.Enlarge(decoration_insets.width(), decoration_insets.height()); return size; } views::View* ClientFrameViewLinux::TargetForRect(views::View* root, const gfx::Rect& rect) { return views::NonClientFrameView::TargetForRect(root, rect); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
patches/chromium/desktop_media_list.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Thu, 18 Oct 2018 17:07:01 -0700 Subject: desktop_media_list.patch * Use our grit resources instead of the chrome ones. * Disabled WindowCaptureMacV2 feature for https://github.com/electron/electron/pull/30507 * Ensure "OnRefreshComplete()" even if there are no items in the list diff --git a/chrome/browser/media/webrtc/desktop_media_list.h b/chrome/browser/media/webrtc/desktop_media_list.h index 42da00a0f473928263df89f11d80830b6986292b..6a556939d0acfbd910ebb0923e198e2fe67fd43d 100644 --- a/chrome/browser/media/webrtc/desktop_media_list.h +++ b/chrome/browser/media/webrtc/desktop_media_list.h @@ -107,7 +107,8 @@ class DesktopMediaList { // once per DesktopMediaList instance. It should not be called after // StartUpdating(), and StartUpdating() should not be called until |callback| // has been called. - virtual void Update(UpdateCallback callback) = 0; + virtual void Update(UpdateCallback callback, + bool refresh_thumbnails = false) = 0; virtual int GetSourceCount() const = 0; virtual const Source& GetSource(int index) const = 0; diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.cc b/chrome/browser/media/webrtc/desktop_media_list_base.cc index 0389599ac786b6abd61ca921347fe12ddd5d0ee7..780927301744ea7312f230cec76a24a33d71f767 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.cc +++ b/chrome/browser/media/webrtc/desktop_media_list_base.cc @@ -69,12 +69,12 @@ void DesktopMediaListBase::StartUpdating(DesktopMediaListObserver* observer) { Refresh(true); } -void DesktopMediaListBase::Update(UpdateCallback callback) { +void DesktopMediaListBase::Update(UpdateCallback callback, bool refresh_thumbnails) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(sources_.empty()); DCHECK(!refresh_callback_); refresh_callback_ = std::move(callback); - Refresh(false); + Refresh(refresh_thumbnails); } int DesktopMediaListBase::GetSourceCount() const { diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.h b/chrome/browser/media/webrtc/desktop_media_list_base.h index f25dede94beab46120194bd5450882fa30a2ad8d..e74071f9e82cb89d0f3eba8ff86e01d67207f1d3 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.h +++ b/chrome/browser/media/webrtc/desktop_media_list_base.h @@ -39,7 +39,7 @@ class DesktopMediaListBase : public DesktopMediaList { void SetThumbnailSize(const gfx::Size& thumbnail_size) override; void SetViewDialogWindowId(content::DesktopMediaID dialog_id) override; void StartUpdating(DesktopMediaListObserver* observer) override; - void Update(UpdateCallback callback) override; + void Update(UpdateCallback callback, bool refresh_thumbnails) override; int GetSourceCount() const override; const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/fake_desktop_media_list.cc b/chrome/browser/media/webrtc/fake_desktop_media_list.cc index 832e0da5271d6ac92466c84dba6917041f825f96..068e7f57be13a89889047abeddd07dfc03b1fce0 100644 --- a/chrome/browser/media/webrtc/fake_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/fake_desktop_media_list.cc @@ -79,7 +79,8 @@ void FakeDesktopMediaList::StartUpdating(DesktopMediaListObserver* observer) { thumbnail_ = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); } -void FakeDesktopMediaList::Update(UpdateCallback callback) { +void FakeDesktopMediaList::Update(UpdateCallback callback, + bool refresh_thumbnails) { std::move(callback).Run(); } diff --git a/chrome/browser/media/webrtc/fake_desktop_media_list.h b/chrome/browser/media/webrtc/fake_desktop_media_list.h index 33ca7a53dfb6d2c9e3a33f0065a3acd806e82e01..9fdf2e8ff0056ff407015b914c6b03eb6e25e0e4 100644 --- a/chrome/browser/media/webrtc/fake_desktop_media_list.h +++ b/chrome/browser/media/webrtc/fake_desktop_media_list.h @@ -40,7 +40,8 @@ class FakeDesktopMediaList : public DesktopMediaList { void SetThumbnailSize(const gfx::Size& thumbnail_size) override; void SetViewDialogWindowId(content::DesktopMediaID dialog_id) override; void StartUpdating(DesktopMediaListObserver* observer) override; - void Update(UpdateCallback callback) override; + void Update(UpdateCallback callback, + bool refresh_thumbnails = false) override; int GetSourceCount() const override; const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chrome/browser/media/webrtc/native_desktop_media_list.cc index b548c9fbd3c0bf425447b29dcd866cd27e96b14c..f994ac6086c7b4cd3e8534f34691189d78a21601 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list.cc @@ -147,7 +147,7 @@ BOOL CALLBACK AllHwndCollector(HWND hwnd, LPARAM param) { #if BUILDFLAG(IS_MAC) BASE_FEATURE(kWindowCaptureMacV2, "WindowCaptureMacV2", - base::FEATURE_ENABLED_BY_DEFAULT); + base::FEATURE_DISABLED_BY_DEFAULT); #endif } // namespace @@ -457,6 +457,9 @@ void NativeDesktopMediaList::Worker::RefreshNextThumbnail() { FROM_HERE, base::BindOnce(&NativeDesktopMediaList::UpdateNativeThumbnailsFinished, media_list_)); + + // This call is necessary to release underlying OS screen capture mechanisms. + capturer_.reset(); } void NativeDesktopMediaList::Worker::OnCaptureResult( @@ -829,6 +832,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( FROM_HERE, base::BindOnce(&Worker::RefreshThumbnails, base::Unretained(worker_.get()), std::move(native_ids), thumbnail_size_)); + } else { +#if defined(USE_AURA) + pending_native_thumbnail_capture_ = true; +#endif + UpdateNativeThumbnailsFinished(); } }
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); window_capturer_->Update( base::BindOnce(&DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()), /* refresh_thumbnails = */ true); } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); screen_capturer_->Update( base::BindOnce(&DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()), /* refresh_thumbnails = */ true); } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
shell/browser/api/electron_api_desktop_capturer.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_ #include <memory> #include <string> #include <vector> #include "chrome/browser/media/webrtc/desktop_media_list_observer.h" #include "chrome/browser/media/webrtc/native_desktop_media_list.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/common/gin_helper/pinnable.h" namespace electron::api { class DesktopCapturer : public gin::Wrappable<DesktopCapturer>, public gin_helper::Pinnable<DesktopCapturer>, public DesktopMediaListObserver { public: struct Source { DesktopMediaList::Source media_list_source; // Will be an empty string if not available. std::string display_id; // Whether or not this source should provide an icon. bool fetch_icon = false; }; static gin::Handle<DesktopCapturer> Create(v8::Isolate* isolate); void StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; const char* GetTypeName() override; // disable copy DesktopCapturer(const DesktopCapturer&) = delete; DesktopCapturer& operator=(const DesktopCapturer&) = delete; protected: explicit DesktopCapturer(v8::Isolate* isolate); ~DesktopCapturer() override; // DesktopMediaListObserver: void OnSourceAdded(int index) override {} void OnSourceRemoved(int index) override {} void OnSourceMoved(int old_index, int new_index) override {} void OnSourceNameChanged(int index) override {} void OnSourceThumbnailChanged(int index) override {} void OnSourcePreviewChanged(size_t index) override {} void OnDelegatedSourceListSelection() override {} void OnDelegatedSourceListDismissed() override {} private: void UpdateSourcesList(DesktopMediaList* list); std::unique_ptr<DesktopMediaList> window_capturer_; std::unique_ptr<DesktopMediaList> screen_capturer_; std::vector<DesktopCapturer::Source> captured_sources_; bool capture_window_ = false; bool capture_screen_ = false; bool fetch_window_icons_ = false; #if BUILDFLAG(IS_WIN) bool using_directx_capturer_ = false; #endif // BUILDFLAG(IS_WIN) base::WeakPtrFactory<DesktopCapturer> weak_ptr_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
patches/chromium/desktop_media_list.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Thu, 18 Oct 2018 17:07:01 -0700 Subject: desktop_media_list.patch * Use our grit resources instead of the chrome ones. * Disabled WindowCaptureMacV2 feature for https://github.com/electron/electron/pull/30507 * Ensure "OnRefreshComplete()" even if there are no items in the list diff --git a/chrome/browser/media/webrtc/desktop_media_list.h b/chrome/browser/media/webrtc/desktop_media_list.h index 42da00a0f473928263df89f11d80830b6986292b..6a556939d0acfbd910ebb0923e198e2fe67fd43d 100644 --- a/chrome/browser/media/webrtc/desktop_media_list.h +++ b/chrome/browser/media/webrtc/desktop_media_list.h @@ -107,7 +107,8 @@ class DesktopMediaList { // once per DesktopMediaList instance. It should not be called after // StartUpdating(), and StartUpdating() should not be called until |callback| // has been called. - virtual void Update(UpdateCallback callback) = 0; + virtual void Update(UpdateCallback callback, + bool refresh_thumbnails = false) = 0; virtual int GetSourceCount() const = 0; virtual const Source& GetSource(int index) const = 0; diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.cc b/chrome/browser/media/webrtc/desktop_media_list_base.cc index 0389599ac786b6abd61ca921347fe12ddd5d0ee7..780927301744ea7312f230cec76a24a33d71f767 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.cc +++ b/chrome/browser/media/webrtc/desktop_media_list_base.cc @@ -69,12 +69,12 @@ void DesktopMediaListBase::StartUpdating(DesktopMediaListObserver* observer) { Refresh(true); } -void DesktopMediaListBase::Update(UpdateCallback callback) { +void DesktopMediaListBase::Update(UpdateCallback callback, bool refresh_thumbnails) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(sources_.empty()); DCHECK(!refresh_callback_); refresh_callback_ = std::move(callback); - Refresh(false); + Refresh(refresh_thumbnails); } int DesktopMediaListBase::GetSourceCount() const { diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.h b/chrome/browser/media/webrtc/desktop_media_list_base.h index f25dede94beab46120194bd5450882fa30a2ad8d..e74071f9e82cb89d0f3eba8ff86e01d67207f1d3 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.h +++ b/chrome/browser/media/webrtc/desktop_media_list_base.h @@ -39,7 +39,7 @@ class DesktopMediaListBase : public DesktopMediaList { void SetThumbnailSize(const gfx::Size& thumbnail_size) override; void SetViewDialogWindowId(content::DesktopMediaID dialog_id) override; void StartUpdating(DesktopMediaListObserver* observer) override; - void Update(UpdateCallback callback) override; + void Update(UpdateCallback callback, bool refresh_thumbnails) override; int GetSourceCount() const override; const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/fake_desktop_media_list.cc b/chrome/browser/media/webrtc/fake_desktop_media_list.cc index 832e0da5271d6ac92466c84dba6917041f825f96..068e7f57be13a89889047abeddd07dfc03b1fce0 100644 --- a/chrome/browser/media/webrtc/fake_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/fake_desktop_media_list.cc @@ -79,7 +79,8 @@ void FakeDesktopMediaList::StartUpdating(DesktopMediaListObserver* observer) { thumbnail_ = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); } -void FakeDesktopMediaList::Update(UpdateCallback callback) { +void FakeDesktopMediaList::Update(UpdateCallback callback, + bool refresh_thumbnails) { std::move(callback).Run(); } diff --git a/chrome/browser/media/webrtc/fake_desktop_media_list.h b/chrome/browser/media/webrtc/fake_desktop_media_list.h index 33ca7a53dfb6d2c9e3a33f0065a3acd806e82e01..9fdf2e8ff0056ff407015b914c6b03eb6e25e0e4 100644 --- a/chrome/browser/media/webrtc/fake_desktop_media_list.h +++ b/chrome/browser/media/webrtc/fake_desktop_media_list.h @@ -40,7 +40,8 @@ class FakeDesktopMediaList : public DesktopMediaList { void SetThumbnailSize(const gfx::Size& thumbnail_size) override; void SetViewDialogWindowId(content::DesktopMediaID dialog_id) override; void StartUpdating(DesktopMediaListObserver* observer) override; - void Update(UpdateCallback callback) override; + void Update(UpdateCallback callback, + bool refresh_thumbnails = false) override; int GetSourceCount() const override; const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chrome/browser/media/webrtc/native_desktop_media_list.cc index b548c9fbd3c0bf425447b29dcd866cd27e96b14c..f994ac6086c7b4cd3e8534f34691189d78a21601 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list.cc @@ -147,7 +147,7 @@ BOOL CALLBACK AllHwndCollector(HWND hwnd, LPARAM param) { #if BUILDFLAG(IS_MAC) BASE_FEATURE(kWindowCaptureMacV2, "WindowCaptureMacV2", - base::FEATURE_ENABLED_BY_DEFAULT); + base::FEATURE_DISABLED_BY_DEFAULT); #endif } // namespace @@ -457,6 +457,9 @@ void NativeDesktopMediaList::Worker::RefreshNextThumbnail() { FROM_HERE, base::BindOnce(&NativeDesktopMediaList::UpdateNativeThumbnailsFinished, media_list_)); + + // This call is necessary to release underlying OS screen capture mechanisms. + capturer_.reset(); } void NativeDesktopMediaList::Worker::OnCaptureResult( @@ -829,6 +832,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( FROM_HERE, base::BindOnce(&Worker::RefreshThumbnails, base::Unretained(worker_.get()), std::move(native_ids), thumbnail_size_)); + } else { +#if defined(USE_AURA) + pending_native_thumbnail_capture_ = true; +#endif + UpdateNativeThumbnailsFinished(); } }
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); window_capturer_->Update( base::BindOnce(&DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()), /* refresh_thumbnails = */ true); } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); screen_capturer_->Update( base::BindOnce(&DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()), /* refresh_thumbnails = */ true); } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,463
[Bug]: DesktopCapturer doesn't work in Ubuntu 22.04.2 LTS
### 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? Ubuntu ### Operating System Version 22.04.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Get access to screens for capture recording using desktopCapturer in electron Api ### Actual Behavior There are difficulties to report the problem because no specific error is received in the terminal, only the message below ```bash tiago@tghpereira:~/Área de Trabalho/electron/test$ yarn start yarn run v1.22.19 $ electron . /home/tiago/Área de Trabalho/electron/test/node_modules/electron/dist/electron exited with signal SIGSEGV error Command failed with exit code 1. ``` I followed the official Electronjs documentation step by step and tried several approaches mentioned in forums to find ways to solve the problem, but without success. Please help us with this issue which is greatly affecting many packages. ### Testcase Gist URL https://gist.github.com/68498fa7437a78b9daf435f3413c9a43 ### Additional Information _No response_
https://github.com/electron/electron/issues/37463
https://github.com/electron/electron/pull/38833
3e3152008ff569632e0b36d53ac9a24fae515709
905e41bbddd72f4d19c294b430d1a7c282e22a5d
2023-03-01T16:20:13Z
c++
2023-07-11T08:21:11Z
shell/browser/api/electron_api_desktop_capturer.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_ #include <memory> #include <string> #include <vector> #include "chrome/browser/media/webrtc/desktop_media_list_observer.h" #include "chrome/browser/media/webrtc/native_desktop_media_list.h" #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/common/gin_helper/pinnable.h" namespace electron::api { class DesktopCapturer : public gin::Wrappable<DesktopCapturer>, public gin_helper::Pinnable<DesktopCapturer>, public DesktopMediaListObserver { public: struct Source { DesktopMediaList::Source media_list_source; // Will be an empty string if not available. std::string display_id; // Whether or not this source should provide an icon. bool fetch_icon = false; }; static gin::Handle<DesktopCapturer> Create(v8::Isolate* isolate); void StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( v8::Isolate* isolate) override; const char* GetTypeName() override; // disable copy DesktopCapturer(const DesktopCapturer&) = delete; DesktopCapturer& operator=(const DesktopCapturer&) = delete; protected: explicit DesktopCapturer(v8::Isolate* isolate); ~DesktopCapturer() override; // DesktopMediaListObserver: void OnSourceAdded(int index) override {} void OnSourceRemoved(int index) override {} void OnSourceMoved(int old_index, int new_index) override {} void OnSourceNameChanged(int index) override {} void OnSourceThumbnailChanged(int index) override {} void OnSourcePreviewChanged(size_t index) override {} void OnDelegatedSourceListSelection() override {} void OnDelegatedSourceListDismissed() override {} private: void UpdateSourcesList(DesktopMediaList* list); std::unique_ptr<DesktopMediaList> window_capturer_; std::unique_ptr<DesktopMediaList> screen_capturer_; std::vector<DesktopCapturer::Source> captured_sources_; bool capture_window_ = false; bool capture_screen_ = false; bool fetch_window_icons_ = false; #if BUILDFLAG(IS_WIN) bool using_directx_capturer_ = false; #endif // BUILDFLAG(IS_WIN) base::WeakPtrFactory<DesktopCapturer> weak_ptr_factory_{this}; }; } // namespace electron::api #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_DESKTOP_CAPTURER_H_
closed
electron/electron
https://github.com/electron/electron
39,031
[Bug]: protocol.handle() is not working with file protocol
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version 6.4.1-arch2-1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When using `protocol.handle()` to intercept the `file` protocol, the handler should be called and `handle()` should be intercepting the request. ### Actual Behavior `protocol.handle()` is not calling the handler and the request finishes without going through the interceptor. ### Testcase Gist URL https://gist.github.com/Aasim-A/87b30a9acf3b4cbc61e8102290f9197b ### Additional Information When I try to do the same thing with `http` or any custom protocol, it works without any issues.
https://github.com/electron/electron/issues/39031
https://github.com/electron/electron/pull/39048
f959fb0c963701c40f309eb8256530f788d5851e
b142fce229c5821083ad6b7c9aa6aa5790032127
2023-07-09T14:52:37Z
c++
2023-07-12T09:42:49Z
lib/browser/api/protocol.ts
import { ProtocolRequest, session } from 'electron/main'; import { createReadStream } from 'fs'; import { Readable } from 'stream'; import { ReadableStream } from 'stream/web'; // Global protocol APIs. const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol'); const ERR_FAILED = -2; const ERR_UNEXPECTED = -9; const isBuiltInScheme = (scheme: string) => scheme === 'http' || scheme === 'https'; function makeStreamFromPipe (pipe: any): ReadableStream { const buf = new Uint8Array(1024 * 1024 /* 1 MB */); return new ReadableStream({ async pull (controller) { try { const rv = await pipe.read(buf); if (rv > 0) { controller.enqueue(buf.subarray(0, rv)); } else { controller.close(); } } catch (e) { controller.error(e); } } }); } function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] { if (!uploadData) return null; // Optimization: skip creating a stream if the request is just a single buffer. if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes; const chunks = [...uploadData] as any[]; // TODO: types are wrong let current: ReadableStreamDefaultReader | null = null; return new ReadableStream({ pull (controller) { if (current) { current.read().then(({ done, value }) => { controller.enqueue(value); if (done) current = null; }, (err) => { controller.error(err); }); } else { if (!chunks.length) { return controller.close(); } const chunk = chunks.shift()!; if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') { current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader(); this.pull!(controller); } else if (chunk.type === 'stream') { current = makeStreamFromPipe(chunk.body).getReader(); this.pull!(controller); } } } }) as RequestInit['body']; } // TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022. function validateResponse (res: Response) { if (!res || typeof res !== 'object') return false; if (res.type === 'error') return true; const exists = (key: string) => Object.hasOwn(res, key); if (exists('status') && typeof res.status !== 'number') return false; if (exists('statusText') && typeof res.statusText !== 'string') return false; if (exists('headers') && typeof res.headers !== 'object') return false; if (exists('body')) { if (typeof res.body !== 'object') return false; if (res.body !== null && !(res.body instanceof ReadableStream)) return false; } return true; } Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) { const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol; const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => { try { const body = convertToRequestBody(preq.uploadData); const req = new Request(preq.url, { headers: preq.headers, method: preq.method, referrer: preq.referrer, body, duplex: body instanceof ReadableStream ? 'half' : undefined } as any); const res = await handler(req); if (!validateResponse(res)) { return cb({ error: ERR_UNEXPECTED }); } else if (res.type === 'error') { cb({ error: ERR_FAILED }); } else { cb({ data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null, headers: res.headers ? Object.fromEntries(res.headers) : {}, statusCode: res.status, statusText: res.statusText, mimeType: (res as any).__original_resp?._responseHead?.mimeType }); } } catch (e) { console.error(e); cb({ error: ERR_UNEXPECTED }); } }); if (!success) throw new Error(`Failed to register protocol: ${scheme}`); }; Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) { const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol; if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); } }; Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) { const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered; return isRegistered.call(this, scheme); }; const protocol = { registerSchemesAsPrivileged, getStandardSchemes, registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args), registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args), registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args), registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args), registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args), registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args), unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args), isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args), interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args), interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args), interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args), interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args), interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args), interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args), uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args), isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args), handle: (...args) => session.defaultSession.protocol.handle(...args), unhandle: (...args) => session.defaultSession.protocol.unhandle(...args), isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args) } as typeof Electron.protocol; export default protocol;
closed
electron/electron
https://github.com/electron/electron
39,031
[Bug]: protocol.handle() is not working with file protocol
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version 6.4.1-arch2-1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When using `protocol.handle()` to intercept the `file` protocol, the handler should be called and `handle()` should be intercepting the request. ### Actual Behavior `protocol.handle()` is not calling the handler and the request finishes without going through the interceptor. ### Testcase Gist URL https://gist.github.com/Aasim-A/87b30a9acf3b4cbc61e8102290f9197b ### Additional Information When I try to do the same thing with `http` or any custom protocol, it works without any issues.
https://github.com/electron/electron/issues/39031
https://github.com/electron/electron/pull/39048
f959fb0c963701c40f309eb8256530f788d5851e
b142fce229c5821083ad6b7c9aa6aa5790032127
2023-07-09T14:52:37Z
c++
2023-07-12T09:42:49Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main'; import * as ChildProcess from 'node:child_process'; import * as path from 'node:path'; import * as url from 'node:url'; import * as http from 'node:http'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as stream from 'node:stream'; import { EventEmitter, once } from 'node:events'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import { WebmGenerator } from './lib/video-helpers'; import { listen, defer, ifit } from './lib/spec-helpers'; import { setTimeout } from 'node:timers/promises'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { // allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks // the stream isn't done when the readable half ends. const body = new stream.PassThrough({ allowHalfOpen: false }); async function sendChunks () { await setTimeout(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await setTimeout(10); } body.push(null); } sendChunks(); return body; } function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> { return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>; } // A promise that can be resolved externally. function deferPromise (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); }); after(() => contents.destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); for (const [registerStringProtocol, name] of [ [protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerBufferProtocol, name] of [ [protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); if (name !== 'protocol.registerProtocol') { it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); } }); } for (const [registerFileProtocol, name] of [ [protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); afterEach(closeAllWindows); if (name === 'protocol.registerFileProtocol') { it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); } it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it('can load iframes with custom protocols', (done) => { registerFileProtocol('custom', (request, callback) => { const filename = request.url.substring(9); const p = path.join(__dirname, 'fixtures', 'pages', filename); callback({ path: p }); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html')); ipcMain.once('loaded-iframe-custom-protocol', () => done()); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerHttpProtocol, name] of [ [protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); const { url } = await listen(server); registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); const { port } = await listen(server); const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); } for (const [registerStreamProtocol, name] of [ [protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = once(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = once(events, 'respond'); const hasClosedPromise = once(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); } describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); const { url } = await listen(server); interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await once(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = deferPromise(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); const { url } = await listen(server); const content = `<script>fetch(${JSON.stringify(url)})</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // DISABLED-FIXME: Figure out why this test is failing it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await once(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await once(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('handle', () => { afterEach(closeAllWindows); it('receives requests to a custom scheme', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(200); }); it('can be unhandled', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { try { // In case of failure, make sure we unhandle. But we should succeed // :) protocol.unhandle('test-scheme'); } catch (_ignored) { /* ignore */ } }); const resp1 = await net.fetch('test-scheme://foo'); expect(resp1.status).to.equal(200); protocol.unhandle('test-scheme'); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/); }); it('receives requests to an existing scheme', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const body = await net.fetch('https://foo').then(r => r.text()); expect(body).to.equal('hello https://foo/'); }); it('receives requests to an existing scheme when navigating', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const w = new BrowserWindow({ show: false }); await w.loadURL('https://localhost'); expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/'); }); it('can send buffer body', async () => { protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url))); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('hello test-scheme://foo'); }); it('can send stream body', async () => { protocol.handle('test-scheme', () => new Response(getWebStream())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('accepts urls with no hostname in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('test-scheme://foo'); } { const body = await net.fetch('test-scheme:///foo').then(r => r.text()); expect(body).to.equal('test-scheme:///foo'); } { const body = await net.fetch('test-scheme://').then(r => r.text()); expect(body).to.equal('test-scheme://'); } }); it('accepts urls with a port-like component in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo:30').then(r => r.text()); expect(body).to.equal('test-scheme://foo:30'); } }); it('normalizes urls in standard schemes', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('app', (req) => new Response(req.url)); defer(() => { protocol.unhandle('app'); }); { const body = await net.fetch('app://foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } { const body = await net.fetch('app:///foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } // NB. 'app' is registered with the default scheme type of 'host'. { const body = await net.fetch('app://foo:1234').then(r => r.text()); expect(body).to.equal('app://foo/'); } await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL'); }); it('fails on URLs with a username', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/); }); it('normalizes http urls', async () => { protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); { const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('http://foo/'); } }); it('can send errors', async () => { protocol.handle('test-scheme', () => Response.error()); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('handles invalid protocol response status', async () => { protocol.handle('test-scheme', () => { return { status: [] } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response statusText', async () => { protocol.handle('test-scheme', () => { return { statusText: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response header parameters', async () => { protocol.handle('test-scheme', () => { return { headers: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response body parameters', async () => { protocol.handle('test-scheme', () => { return { body: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles a synchronous error in the handler', async () => { protocol.handle('test-scheme', () => { throw new Error('test'); }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles an asynchronous error in the handler', async () => { protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise'))); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('correctly sets statusCode', async () => { protocol.handle('test-scheme', () => new Response(null, { status: 201 })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(201); }); it('correctly sets content-type and charset', async () => { protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset'); }); it('can forward to http', async () => { const server = http.createServer((req, res) => { res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', () => net.fetch(url)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('can forward an http request with headers', async () => { const server = http.createServer((req, res) => { res.setHeader('foo', 'bar'); res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('foo')).to.equal('bar'); }); it('can forward to file', async () => { protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body.trimEnd()).to.equal('hello world'); }); it('can receive simple request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: 'foobar' }).then(r => r.text()); expect(body).to.equal('foobar'); }); it('can receive stream request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: getWebStream(), duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157 } as any).then(r => r.text()); expect(body).to.equal(text); }); it('can receive multi-part postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab'); }); it('can receive file postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n'); }); it('can receive file postData from a form', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>'); const { debugger: dbg } = contents; dbg.attach(); const { root } = await dbg.sendCommand('DOM.getDocument'); const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' }); await dbg.sendCommand('DOM.setFileInputFiles', { nodeId: fileInputNodeId, files: [ path.join(fixturesPath, 'hello.txt') ] }); const navigated = once(contents, 'did-finish-load'); await contents.executeJavaScript('document.querySelector("form").submit()'); await navigated; expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/); }); it('can receive streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive streaming fetch upload when a webRequest handler is present', async () => { session.defaultSession.webRequest.onBeforeRequest((details, cb) => { console.log('webRequest', details.url, details.method); cb({}); }); defer(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); protocol.handle('no-cors', (req) => { console.log('handle', req.url, req.method); return new Response(req.body); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive an error from streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.error('test') }, }); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); expect(fetchBodyResult).to.be.an.instanceOf(Error); }); it('gets an error from streaming fetch upload when the renderer dies', async () => { let gotRequest: Function; const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; }); protocol.handle('no-cors', (req) => { if (/fetch/.test(req.url)) gotRequest(req); return new Response(); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { window.controller = controller // no GC }, }); fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); const req = await receivedRequest; contents.destroy(); // Undo .destroy() for the next test contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('can bypass intercepeted protocol handlers', async () => { protocol.handle('http', () => new Response('custom')); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('default'); }); defer(() => server.close()); const { url } = await listen(server); expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default'); }); it('bypassing custom protocol handlers also bypasses new protocols', async () => { protocol.handle('app', () => new Response('custom')); defer(() => { protocol.unhandle('app'); }); await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME'); }); it('can forward to the original handler', async () => { protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true })); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('hello'); server.close(); }); const { url } = await listen(server); await contents.loadURL(url); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello'); }); it('supports sniffing mime type', async () => { protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); } }); const { url } = await listen(server); defer(() => server.close()); { await contents.loadURL(url); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.match(/white-space: pre-wrap/); } { await contents.loadURL(url + '?html'); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.equal('<html><head></head><body>hi</body></html>'); } }); // TODO(nornagon): this test doesn't pass on Linux currently, investigate. ifit(process.platform !== 'linux')('is fast', async () => { // 128 MB of spaces. const chunk = new Uint8Array(128 * 1024 * 1024); chunk.fill(' '.charCodeAt(0)); const server = http.createServer((req, res) => { // The sniffed mime type for the space-filled chunk will be // text/plain, which chews up all its performance in the renderer // trying to wrap lines. Setting content-type to text/html measures // something closer to just the raw cost of getting the bytes over // the wire. res.setHeader('content-type', 'text/html'); res.end(chunk); }); defer(() => server.close()); const { url } = await listen(server); const rawTime = await (async () => { await contents.loadURL(url); // warm const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); // Fetching through an intercepted handler should not be too much slower // than it would be if the protocol hadn't been intercepted. protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const interceptedTime = await (async () => { const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); expect(interceptedTime).to.be.lessThan(rawTime * 1.5); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,031
[Bug]: protocol.handle() is not working with file protocol
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version 6.4.1-arch2-1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When using `protocol.handle()` to intercept the `file` protocol, the handler should be called and `handle()` should be intercepting the request. ### Actual Behavior `protocol.handle()` is not calling the handler and the request finishes without going through the interceptor. ### Testcase Gist URL https://gist.github.com/Aasim-A/87b30a9acf3b4cbc61e8102290f9197b ### Additional Information When I try to do the same thing with `http` or any custom protocol, it works without any issues.
https://github.com/electron/electron/issues/39031
https://github.com/electron/electron/pull/39048
f959fb0c963701c40f309eb8256530f788d5851e
b142fce229c5821083ad6b7c9aa6aa5790032127
2023-07-09T14:52:37Z
c++
2023-07-12T09:42:49Z
lib/browser/api/protocol.ts
import { ProtocolRequest, session } from 'electron/main'; import { createReadStream } from 'fs'; import { Readable } from 'stream'; import { ReadableStream } from 'stream/web'; // Global protocol APIs. const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol'); const ERR_FAILED = -2; const ERR_UNEXPECTED = -9; const isBuiltInScheme = (scheme: string) => scheme === 'http' || scheme === 'https'; function makeStreamFromPipe (pipe: any): ReadableStream { const buf = new Uint8Array(1024 * 1024 /* 1 MB */); return new ReadableStream({ async pull (controller) { try { const rv = await pipe.read(buf); if (rv > 0) { controller.enqueue(buf.subarray(0, rv)); } else { controller.close(); } } catch (e) { controller.error(e); } } }); } function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] { if (!uploadData) return null; // Optimization: skip creating a stream if the request is just a single buffer. if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes; const chunks = [...uploadData] as any[]; // TODO: types are wrong let current: ReadableStreamDefaultReader | null = null; return new ReadableStream({ pull (controller) { if (current) { current.read().then(({ done, value }) => { controller.enqueue(value); if (done) current = null; }, (err) => { controller.error(err); }); } else { if (!chunks.length) { return controller.close(); } const chunk = chunks.shift()!; if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') { current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader(); this.pull!(controller); } else if (chunk.type === 'stream') { current = makeStreamFromPipe(chunk.body).getReader(); this.pull!(controller); } } } }) as RequestInit['body']; } // TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022. function validateResponse (res: Response) { if (!res || typeof res !== 'object') return false; if (res.type === 'error') return true; const exists = (key: string) => Object.hasOwn(res, key); if (exists('status') && typeof res.status !== 'number') return false; if (exists('statusText') && typeof res.statusText !== 'string') return false; if (exists('headers') && typeof res.headers !== 'object') return false; if (exists('body')) { if (typeof res.body !== 'object') return false; if (res.body !== null && !(res.body instanceof ReadableStream)) return false; } return true; } Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) { const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol; const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => { try { const body = convertToRequestBody(preq.uploadData); const req = new Request(preq.url, { headers: preq.headers, method: preq.method, referrer: preq.referrer, body, duplex: body instanceof ReadableStream ? 'half' : undefined } as any); const res = await handler(req); if (!validateResponse(res)) { return cb({ error: ERR_UNEXPECTED }); } else if (res.type === 'error') { cb({ error: ERR_FAILED }); } else { cb({ data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null, headers: res.headers ? Object.fromEntries(res.headers) : {}, statusCode: res.status, statusText: res.statusText, mimeType: (res as any).__original_resp?._responseHead?.mimeType }); } } catch (e) { console.error(e); cb({ error: ERR_UNEXPECTED }); } }); if (!success) throw new Error(`Failed to register protocol: ${scheme}`); }; Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) { const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol; if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); } }; Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) { const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered; return isRegistered.call(this, scheme); }; const protocol = { registerSchemesAsPrivileged, getStandardSchemes, registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args), registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args), registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args), registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args), registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args), registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args), unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args), isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args), interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args), interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args), interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args), interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args), interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args), interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args), uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args), isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args), handle: (...args) => session.defaultSession.protocol.handle(...args), unhandle: (...args) => session.defaultSession.protocol.unhandle(...args), isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args) } as typeof Electron.protocol; export default protocol;
closed
electron/electron
https://github.com/electron/electron
39,031
[Bug]: protocol.handle() is not working with file protocol
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 25.2.0 ### What operating system are you using? Other Linux ### Operating System Version 6.4.1-arch2-1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior When using `protocol.handle()` to intercept the `file` protocol, the handler should be called and `handle()` should be intercepting the request. ### Actual Behavior `protocol.handle()` is not calling the handler and the request finishes without going through the interceptor. ### Testcase Gist URL https://gist.github.com/Aasim-A/87b30a9acf3b4cbc61e8102290f9197b ### Additional Information When I try to do the same thing with `http` or any custom protocol, it works without any issues.
https://github.com/electron/electron/issues/39031
https://github.com/electron/electron/pull/39048
f959fb0c963701c40f309eb8256530f788d5851e
b142fce229c5821083ad6b7c9aa6aa5790032127
2023-07-09T14:52:37Z
c++
2023-07-12T09:42:49Z
spec/api-protocol-spec.ts
import { expect } from 'chai'; import { v4 } from 'uuid'; import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main'; import * as ChildProcess from 'node:child_process'; import * as path from 'node:path'; import * as url from 'node:url'; import * as http from 'node:http'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as stream from 'node:stream'; import { EventEmitter, once } from 'node:events'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import { WebmGenerator } from './lib/video-helpers'; import { listen, defer, ifit } from './lib/spec-helpers'; import { setTimeout } from 'node:timers/promises'; const fixturesPath = path.resolve(__dirname, 'fixtures'); const registerStringProtocol = protocol.registerStringProtocol; const registerBufferProtocol = protocol.registerBufferProtocol; const registerFileProtocol = protocol.registerFileProtocol; const registerStreamProtocol = protocol.registerStreamProtocol; const interceptStringProtocol = protocol.interceptStringProtocol; const interceptBufferProtocol = protocol.interceptBufferProtocol; const interceptHttpProtocol = protocol.interceptHttpProtocol; const interceptStreamProtocol = protocol.interceptStreamProtocol; const unregisterProtocol = protocol.unregisterProtocol; const uninterceptProtocol = protocol.uninterceptProtocol; const text = 'valar morghulis'; const protocolName = 'no-cors'; const postData = { name: 'post test', type: 'string' }; function getStream (chunkSize = text.length, data: Buffer | string = text) { // allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks // the stream isn't done when the readable half ends. const body = new stream.PassThrough({ allowHalfOpen: false }); async function sendChunks () { await setTimeout(0); // the stream protocol API breaks if you send data immediately. let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer for (;;) { body.push(buf.slice(0, chunkSize)); buf = buf.slice(chunkSize); if (!buf.length) { break; } // emulate some network delay await setTimeout(10); } body.push(null); } sendChunks(); return body; } function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> { return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>; } // A promise that can be resolved externally. function deferPromise (): Promise<any> & {resolve: Function, reject: Function} { let promiseResolve: Function = null as unknown as Function; let promiseReject: Function = null as unknown as Function; const promise: any = new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }); promise.resolve = promiseResolve; promise.reject = promiseReject; return promise; } describe('protocol module', () => { let contents: WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); }); after(() => contents.destroy()); async function ajax (url: string, options = {}) { // Note that we need to do navigation every time after a protocol is // registered or unregistered, otherwise the new protocol won't be // recognized by current page when NetworkService is used. await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`); } afterEach(() => { protocol.unregisterProtocol(protocolName); protocol.uninterceptProtocol('http'); }); describe('protocol.register(Any)Protocol', () => { it('fails when scheme is already registered', () => { expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true); expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { registerStringProtocol(protocolName, (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends error when callback is called with nothing', async () => { registerBufferProtocol(protocolName, (req, cb: any) => cb()); await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected(); }); it('does not crash when callback is called in next tick', async () => { registerStringProtocol(protocolName, (request, callback) => { setImmediate(() => callback(text)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('can redirect to the same scheme', async () => { registerStringProtocol(protocolName, (request, callback) => { if (request.url === `${protocolName}://fake-host/redirect`) { callback({ statusCode: 302, headers: { Location: `${protocolName}://fake-host` } }); } else { expect(request.url).to.equal(`${protocolName}://fake-host`); callback('redirected'); } }); const r = await ajax(`${protocolName}://fake-host/redirect`); expect(r.data).to.equal('redirected'); }); }); describe('protocol.unregisterProtocol', () => { it('returns false when scheme does not exist', () => { expect(unregisterProtocol('not-exist')).to.equal(false); }); }); for (const [registerStringProtocol, name] of [ [protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends string as response', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerStringProtocol(protocolName, (request, callback) => callback(text)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerStringProtocol(protocolName, (request, callback) => { callback({ data: text, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending object other than string', async () => { const notAString = () => {}; registerStringProtocol(protocolName, (request, callback) => callback(notAString as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerBufferProtocol, name] of [ [protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const buffer = Buffer.from(text); it('sends Buffer as response', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sets Access-Control-Allow-Origin', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(buffer)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sends object as response', async () => { registerBufferProtocol(protocolName, (request, callback) => { callback({ data: buffer, mimeType: 'text/html' }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); if (name !== 'protocol.registerProtocol') { it('fails when sending string', async () => { registerBufferProtocol(protocolName, (request, callback) => callback(text as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); } }); } for (const [registerFileProtocol, name] of [ [protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1'); const fileContent = fs.readFileSync(filePath); const normalPath = path.join(fixturesPath, 'pages', 'a.html'); const normalContent = fs.readFileSync(normalPath); afterEach(closeAllWindows); if (name === 'protocol.registerFileProtocol') { it('sends file path as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback(filePath)); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); } it('sets Access-Control-Allow-Origin', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('access-control-allow-origin', '*'); }); it('sets custom headers', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath, headers: { 'X-Great-Header': 'sogreat' } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); it('can load iframes with custom protocols', (done) => { registerFileProtocol('custom', (request, callback) => { const filename = request.url.substring(9); const p = path.join(__dirname, 'fixtures', 'pages', filename); callback({ path: p }); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html')); ipcMain.once('loaded-iframe-custom-protocol', () => done()); }); it('sends object as response', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(fileContent)); }); it('can send normal file', async () => { registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(String(normalContent)); }); it('fails when sending unexist-file', async () => { const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist'); registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); }); } for (const [registerHttpProtocol, name] of [ [protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends url as response', async () => { const server = http.createServer((req, res) => { expect(req.headers.accept).to.not.equal(''); res.end(text); server.close(); }); const { url } = await listen(server); registerHttpProtocol(protocolName, (request, callback) => callback({ url })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('fails when sending invalid url', async () => { registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' })); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('fails when sending unsupported content', async () => { registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any)); await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected(); }); it('works when target URL redirects', async () => { const server = http.createServer((req, res) => { if (req.url === '/serverRedirect') { res.statusCode = 301; res.setHeader('Location', `http://${req.rawHeaders[1]}`); res.end(); } else { res.end(text); } }); after(() => server.close()); const { port } = await listen(server); const url = `${protocolName}://fake-host`; const redirectURL = `http://127.0.0.1:${port}/serverRedirect`; registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL })); const r = await ajax(url); expect(r.data).to.equal(text); }); it('can access request headers', (done) => { protocol.registerHttpProtocol(protocolName, (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax(protocolName + '://fake-host').catch(() => {}); }); }); } for (const [registerStreamProtocol, name] of [ [protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const, [(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const ]) { describe(name, () => { it('sends Stream as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback(getStream())); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); }); it('sends object as response', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); }); it('sends custom response headers', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream(3), headers: { 'x-electron': ['a', 'b'] } })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.equal(text); expect(r.status).to.equal(200); expect(r.headers).to.have.property('x-electron', 'a, b'); }); it('sends custom status code', async () => { registerStreamProtocol(protocolName, (request, callback) => callback({ statusCode: 204, data: null as any })); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.be.empty('data'); expect(r.status).to.equal(204); }); it('receives request headers', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { 'content-type': 'application/json' }, data: getStream(5, JSON.stringify(Object.assign({}, request.headers))) }); }); const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } }); expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes'); }); it('returns response multiple response headers with the same name', async () => { registerStreamProtocol(protocolName, (request, callback) => { callback({ headers: { header1: ['value1', 'value2'], header2: 'value3' }, data: getStream() }); }); const r = await ajax(protocolName + '://fake-host'); // SUBTLE: when the response headers have multiple values it // separates values by ", ". When the response headers are incorrectly // converting an array to a string it separates values by ",". expect(r.headers).to.have.property('header1', 'value1, value2'); expect(r.headers).to.have.property('header2', 'value3'); }); it('can handle large responses', async () => { const data = Buffer.alloc(128 * 1024); registerStreamProtocol(protocolName, (request, callback) => { callback(getStream(data.length, data)); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(data.length); }); it('can handle a stream completing while writing', async () => { function dumbPassthrough () { return new stream.Transform({ async transform (chunk, encoding, cb) { cb(null, chunk); } }); } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough()) }); }); const r = await ajax(protocolName + '://fake-host'); expect(r.data).to.have.lengthOf(1024 * 1024 * 2); }); it('can handle next-tick scheduling during read calls', async () => { const events = new EventEmitter(); function createStream () { const buffers = [ Buffer.alloc(65536), Buffer.alloc(65537), Buffer.alloc(39156) ]; const e = new stream.Readable({ highWaterMark: 0 }); e.push(buffers.shift()); e._read = function () { process.nextTick(() => this.push(buffers.shift() || null)); }; e.on('end', function () { events.emit('end'); }); return e; } registerStreamProtocol(protocolName, (request, callback) => { callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: createStream() }); }); const hasEndedPromise = once(events, 'end'); ajax(protocolName + '://fake-host').catch(() => {}); await hasEndedPromise; }); it('destroys response streams when aborted before completion', async () => { const events = new EventEmitter(); registerStreamProtocol(protocolName, (request, callback) => { const responseStream = new stream.PassThrough(); responseStream.push('data\r\n'); responseStream.on('close', () => { events.emit('close'); }); callback({ statusCode: 200, headers: { 'Content-Type': 'text/plain' }, data: responseStream }); events.emit('respond'); }); const hasRespondedPromise = once(events, 'respond'); const hasClosedPromise = once(events, 'close'); ajax(protocolName + '://fake-host').catch(() => {}); await hasRespondedPromise; await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html')); await hasClosedPromise; }); }); } describe('protocol.isProtocolRegistered', () => { it('returns false when scheme is not registered', () => { const result = protocol.isProtocolRegistered('no-exist'); expect(result).to.be.false('no-exist: is handled'); }); it('returns true for custom protocol', () => { registerStringProtocol(protocolName, (request, callback) => callback('')); const result = protocol.isProtocolRegistered(protocolName); expect(result).to.be.true('custom protocol is handled'); }); }); describe('protocol.isProtocolIntercepted', () => { it('returns true for intercepted protocol', () => { interceptStringProtocol('http', (request, callback) => callback('')); const result = protocol.isProtocolIntercepted('http'); expect(result).to.be.true('intercepted protocol is handled'); }); }); describe('protocol.intercept(Any)Protocol', () => { it('returns false when scheme is already intercepted', () => { expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true); expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false); }); it('does not crash when handler is called twice', async () => { interceptStringProtocol('http', (request, callback) => { try { callback(text); callback(''); } catch (error) { // Ignore error } }); const r = await ajax('http://fake-host'); expect(r.data).to.be.equal(text); }); it('sends error when callback is called with nothing', async () => { interceptStringProtocol('http', (request, callback: any) => callback()); await expect(ajax('http://fake-host')).to.be.eventually.rejected(); }); }); describe('protocol.interceptStringProtocol', () => { it('can intercept http protocol', async () => { interceptStringProtocol('http', (request, callback) => callback(text)); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can set content-type', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can set content-type with charset', async () => { interceptStringProtocol('http', (request, callback) => { callback({ mimeType: 'application/json; charset=UTF-8', data: '{"value": 1}' }); }); const r = await ajax('http://fake-host'); expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1); }); it('can receive post data', async () => { interceptStringProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes.toString(); callback({ data: uploadData }); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); }); describe('protocol.interceptBufferProtocol', () => { it('can intercept http protocol', async () => { interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text))); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptBufferProtocol('http', (request, callback) => { const uploadData = request.uploadData![0].bytes; callback(uploadData); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' }); }); }); describe('protocol.interceptHttpProtocol', () => { // FIXME(zcbenz): This test was passing because the test itself was wrong, // I don't know whether it ever passed before and we should take a look at // it in future. xit('can send POST request', async () => { const server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { res.end(body); }); server.close(); }); after(() => server.close()); const { url } = await listen(server); interceptHttpProtocol('http', (request, callback) => { const data: Electron.ProtocolResponse = { url: url, method: 'POST', uploadData: { contentType: 'application/x-www-form-urlencoded', data: request.uploadData![0].bytes }, session: undefined }; callback(data); }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can use custom session', async () => { const customSession = session.fromPartition('custom-ses', { cache: false }); customSession.webRequest.onBeforeRequest((details, callback) => { expect(details.url).to.equal('http://fake-host/'); callback({ cancel: true }); }); after(() => customSession.webRequest.onBeforeRequest(null)); interceptHttpProtocol('http', (request, callback) => { callback({ url: request.url, session: customSession }); }); await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error); }); it('can access request headers', (done) => { protocol.interceptHttpProtocol('http', (request) => { try { expect(request).to.have.property('headers'); done(); } catch (e) { done(e); } }); ajax('http://fake-host').catch(() => {}); }); }); describe('protocol.interceptStreamProtocol', () => { it('can intercept http protocol', async () => { interceptStreamProtocol('http', (request, callback) => callback(getStream())); const r = await ajax('http://fake-host'); expect(r.data).to.equal(text); }); it('can receive post data', async () => { interceptStreamProtocol('http', (request, callback) => { callback(getStream(3, request.uploadData![0].bytes.toString())); }); const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) }); expect({ ...qs.parse(r.data) }).to.deep.equal(postData); }); it('can execute redirects', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ data: '', statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(1, 'redirect')); } }); const r = await ajax('http://fake-host'); expect(r.data).to.equal('redirect'); }); it('should discard post data after redirection', async () => { interceptStreamProtocol('http', (request, callback) => { if (request.url.indexOf('http://fake-host') === 0) { setTimeout(300).then(() => { callback({ statusCode: 302, headers: { Location: 'http://fake-redirect' } }); }); } else { expect(request.url.indexOf('http://fake-redirect')).to.equal(0); callback(getStream(3, request.method)); } }); const r = await ajax('http://fake-host', { type: 'POST', data: postData }); expect(r.data).to.equal('GET'); }); }); describe('protocol.uninterceptProtocol', () => { it('returns false when scheme does not exist', () => { expect(uninterceptProtocol('not-exist')).to.equal(false); }); it('returns false when scheme is not intercepted', () => { expect(uninterceptProtocol('http')).to.equal(false); }); }); describe('protocol.registerSchemeAsPrivileged', () => { it('does not crash on exit', async () => { const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js'); const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]); let stdout = ''; let stderr = ''; appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; }); appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; }); const [code] = await once(appProcess, 'exit'); if (code !== 0) { console.log('Exit code : ', code); console.log('stdout : ', stdout); console.log('stderr : ', stderr); } expect(code).to.equal(0); expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED'); }); }); describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => { protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => { if (request.url.endsWith('.js')) { cb({ mimeType: 'text/javascript', charset: 'utf-8', data: 'console.log("Loaded")' }); } else { cb({ mimeType: 'text/html', charset: 'utf-8', data: '<!DOCTYPE html>' }); } }); after(() => protocol.unregisterProtocol(serviceWorkerScheme)); it('should fail when registering invalid service worker', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected(); }); it('should be able to register service worker for custom scheme', async () => { await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`); await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`); }); }); describe('protocol.registerSchemesAsPrivileged standard', () => { const origin = `${standardScheme}://fake-host`; const imageURL = `${origin}/test.png`; const filePath = path.join(fixturesPath, 'pages', 'b.html'); const fileContent = '<img src="/test.png" />'; let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); unregisterProtocol(standardScheme); w = null as unknown as BrowserWindow; }); it('resolves relative resources', async () => { registerFileProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback(filePath); } }); await w.loadURL(origin); }); it('resolves absolute resources', async () => { registerStringProtocol(standardScheme, (request, callback) => { if (request.url === imageURL) { callback(''); } else { callback({ data: fileContent, mimeType: 'text/html' }); } }); await w.loadURL(origin); }); it('can have fetch working in it', async () => { const requestReceived = deferPromise(); const server = http.createServer((req, res) => { res.end(); server.close(); requestReceived.resolve(); }); const { url } = await listen(server); const content = `<script>fetch(${JSON.stringify(url)})</script>`; registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' })); await w.loadURL(origin); await requestReceived; }); it('can access files through the FileSystem API', (done) => { const filePath = path.join(fixturesPath, 'pages', 'filesystem.html'); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); ipcMain.once('file-system-error', (event, err) => done(err)); ipcMain.once('file-system-write-end', () => done()); }); it('registers secure, when {secure: true}', (done) => { const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html'); ipcMain.once('success', () => done()); ipcMain.once('failure', (event, err) => done(err)); protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath })); w.loadURL(origin); }); }); describe('protocol.registerSchemesAsPrivileged cors-fetch', function () { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) { protocol.unregisterProtocol(scheme); } }); it('supports fetch api by default', async () => { const url = `file://${fixturesPath}/assets/logo.png`; await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`); expect(ok).to.be.true('response ok'); }); it('allows CORS requests by default', async () => { await allowsCORSRequests('cors', 200, new RegExp(''), () => { const { ipcRenderer } = require('electron'); fetch('cors://myhost').then(function (response) { ipcRenderer.send('response', response.status); }).catch(function () { ipcRenderer.send('response', 'failed'); }); }); }); // DISABLED-FIXME: Figure out why this test is failing it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => { await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-cors://myhost'); req.send(); }), fetch('no-cors://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); it('allows CORS, but disallows fetch requests, when specified', async () => { await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => { const { ipcRenderer } = require('electron'); Promise.all([ new Promise(resolve => { const req = new XMLHttpRequest(); req.onload = () => resolve('loaded xhr'); req.onerror = () => resolve('failed xhr'); req.open('GET', 'no-fetch://myhost'); req.send(); }), fetch('no-fetch://myhost') .then(() => 'loaded fetch') .catch(() => 'failed fetch') ]).then(([xhr, fetch]) => { ipcRenderer.send('response', [xhr, fetch]); }); }); }); async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) { registerStringProtocol(standardScheme, (request, callback) => { callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' }); }); registerStringProtocol(corsScheme, (request, callback) => { callback(''); }); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { newContents.loadURL(standardScheme + '://fake-host'); const [, response] = await once(ipcMain, 'response'); expect(response).to.deep.equal(expected); expect(consoleMessages.join('\n')).to.match(expectedConsole); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('protocol.registerSchemesAsPrivileged stream', async function () { const pagePath = path.join(fixturesPath, 'pages', 'video.html'); const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp'); const videoPath = path.join(fixturesPath, 'video.webm'); let w: BrowserWindow; before(async () => { // generate test video const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64'); const imageDataUrl = `data:image/webp;base64,${imageBase64}`; const encoder = new WebmGenerator(15); for (let i = 0; i < 30; i++) { encoder.add(imageDataUrl); } await new Promise((resolve, reject) => { encoder.compile((output:Uint8Array) => { fs.promises.writeFile(videoPath, output).then(resolve, reject); }); }); }); after(async () => { await fs.promises.unlink(videoPath); }); beforeEach(async function () { w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; await protocol.unregisterProtocol(standardScheme); await protocol.unregisterProtocol('stream'); }); it('successfully plays videos when content is buffered (stream: false)', async () => { await streamsResponses(standardScheme, 'play'); }); it('successfully plays videos when streaming content (stream: true)', async () => { await streamsResponses('stream', 'play'); }); async function streamsResponses (testingScheme: string, expected: any) { const protocolHandler = (request: any, callback: Function) => { if (request.url.includes('/video.webm')) { const stat = fs.statSync(videoPath); const fileSize = stat.size; const range = request.headers.Range; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1; const chunksize = (end - start) + 1; const headers = { 'Content-Range': `bytes ${start}-${end}/${fileSize}`, 'Accept-Ranges': 'bytes', 'Content-Length': String(chunksize), 'Content-Type': 'video/webm' }; callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) }); } else { callback({ statusCode: 200, headers: { 'Content-Length': String(fileSize), 'Content-Type': 'video/webm' }, data: fs.createReadStream(videoPath) }); } } else { callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 }); } }; await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); const newContents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await once(ipcMain, 'result'); expect(response).to.deep.equal(expected); } finally { // This is called in a timeout to avoid a crash that happens when // calling destroy() in a microtask. setTimeout().then(() => { newContents.destroy(); }); } } }); describe('handle', () => { afterEach(closeAllWindows); it('receives requests to a custom scheme', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(200); }); it('can be unhandled', async () => { protocol.handle('test-scheme', (req) => new Response('hello ' + req.url)); defer(() => { try { // In case of failure, make sure we unhandle. But we should succeed // :) protocol.unhandle('test-scheme'); } catch (_ignored) { /* ignore */ } }); const resp1 = await net.fetch('test-scheme://foo'); expect(resp1.status).to.equal(200); protocol.unhandle('test-scheme'); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/); }); it('receives requests to an existing scheme', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const body = await net.fetch('https://foo').then(r => r.text()); expect(body).to.equal('hello https://foo/'); }); it('receives requests to an existing scheme when navigating', async () => { protocol.handle('https', (req) => new Response('hello ' + req.url)); defer(() => { protocol.unhandle('https'); }); const w = new BrowserWindow({ show: false }); await w.loadURL('https://localhost'); expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/'); }); it('can send buffer body', async () => { protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url))); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('hello test-scheme://foo'); }); it('can send stream body', async () => { protocol.handle('test-scheme', () => new Response(getWebStream())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('accepts urls with no hostname in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal('test-scheme://foo'); } { const body = await net.fetch('test-scheme:///foo').then(r => r.text()); expect(body).to.equal('test-scheme:///foo'); } { const body = await net.fetch('test-scheme://').then(r => r.text()); expect(body).to.equal('test-scheme://'); } }); it('accepts urls with a port-like component in non-standard schemes', async () => { protocol.handle('test-scheme', (req) => new Response(req.url)); defer(() => { protocol.unhandle('test-scheme'); }); { const body = await net.fetch('test-scheme://foo:30').then(r => r.text()); expect(body).to.equal('test-scheme://foo:30'); } }); it('normalizes urls in standard schemes', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('app', (req) => new Response(req.url)); defer(() => { protocol.unhandle('app'); }); { const body = await net.fetch('app://foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } { const body = await net.fetch('app:///foo').then(r => r.text()); expect(body).to.equal('app://foo/'); } // NB. 'app' is registered with the default scheme type of 'host'. { const body = await net.fetch('app://foo:1234').then(r => r.text()); expect(body).to.equal('app://foo/'); } await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL'); }); it('fails on URLs with a username', async () => { // NB. 'app' is registered as a standard scheme in test setup. protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/); }); it('normalizes http urls', async () => { protocol.handle('http', (req) => new Response(req.url)); defer(() => { protocol.unhandle('http'); }); { const body = await net.fetch('http://foo').then(r => r.text()); expect(body).to.equal('http://foo/'); } }); it('can send errors', async () => { protocol.handle('test-scheme', () => Response.error()); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('handles invalid protocol response status', async () => { protocol.handle('test-scheme', () => { return { status: [] } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response statusText', async () => { protocol.handle('test-scheme', () => { return { statusText: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response header parameters', async () => { protocol.handle('test-scheme', () => { return { headers: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles invalid protocol response body parameters', async () => { protocol.handle('test-scheme', () => { return { body: false } as any; }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles a synchronous error in the handler', async () => { protocol.handle('test-scheme', () => { throw new Error('test'); }); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('handles an asynchronous error in the handler', async () => { protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise'))); defer(() => { protocol.unhandle('test-scheme'); }); await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED'); }); it('correctly sets statusCode', async () => { protocol.handle('test-scheme', () => new Response(null, { status: 201 })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.status).to.equal(201); }); it('correctly sets content-type and charset', async () => { protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset'); }); it('can forward to http', async () => { const server = http.createServer((req, res) => { res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', () => net.fetch(url)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body).to.equal(text); }); it('can forward an http request with headers', async () => { const server = http.createServer((req, res) => { res.setHeader('foo', 'bar'); res.end(text); }); defer(() => { server.close(); }); const { url } = await listen(server); protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers })); defer(() => { protocol.unhandle('test-scheme'); }); const resp = await net.fetch('test-scheme://foo'); expect(resp.headers.get('foo')).to.equal('bar'); }); it('can forward to file', async () => { protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString())); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo').then(r => r.text()); expect(body.trimEnd()).to.equal('hello world'); }); it('can receive simple request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: 'foobar' }).then(r => r.text()); expect(body).to.equal('foobar'); }); it('can receive stream request body', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); const body = await net.fetch('test-scheme://foo', { method: 'POST', body: getWebStream(), duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157 } as any).then(r => r.text()); expect(body).to.equal(text); }); it('can receive multi-part postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab'); }); it('can receive file postData from loadURL', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] }); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n'); }); it('can receive file postData from a form', async () => { protocol.handle('test-scheme', (req) => new Response(req.body)); defer(() => { protocol.unhandle('test-scheme'); }); await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>'); const { debugger: dbg } = contents; dbg.attach(); const { root } = await dbg.sendCommand('DOM.getDocument'); const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' }); await dbg.sendCommand('DOM.setFileInputFiles', { nodeId: fileInputNodeId, files: [ path.join(fixturesPath, 'hello.txt') ] }); const navigated = once(contents, 'did-finish-load'); await contents.executeJavaScript('document.querySelector("form").submit()'); await navigated; expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/); }); it('can receive streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive streaming fetch upload when a webRequest handler is present', async () => { session.defaultSession.webRequest.onBeforeRequest((details, cb) => { console.log('webRequest', details.url, details.method); cb({}); }); defer(() => { session.defaultSession.webRequest.onBeforeRequest(null); }); protocol.handle('no-cors', (req) => { console.log('handle', req.url, req.method); return new Response(req.body); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.enqueue('hello world'); controller.close(); }, }).pipeThrough(new TextEncoderStream()); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()) `); expect(fetchBodyResult).to.equal('hello world'); }); it('can receive an error from streaming fetch upload', async () => { protocol.handle('no-cors', (req) => new Response(req.body)); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); const fetchBodyResult = await contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { controller.error('test') }, }); fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); expect(fetchBodyResult).to.be.an.instanceOf(Error); }); it('gets an error from streaming fetch upload when the renderer dies', async () => { let gotRequest: Function; const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; }); protocol.handle('no-cors', (req) => { if (/fetch/.test(req.url)) gotRequest(req); return new Response(); }); defer(() => { protocol.unhandle('no-cors'); }); await contents.loadURL('no-cors://foo'); contents.executeJavaScript(` const stream = new ReadableStream({ async start(controller) { window.controller = controller // no GC }, }); fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err) `); const req = await receivedRequest; contents.destroy(); // Undo .destroy() for the next test contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED'); }); it('can bypass intercepeted protocol handlers', async () => { protocol.handle('http', () => new Response('custom')); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('default'); }); defer(() => server.close()); const { url } = await listen(server); expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default'); }); it('bypassing custom protocol handlers also bypasses new protocols', async () => { protocol.handle('app', () => new Response('custom')); defer(() => { protocol.unhandle('app'); }); await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME'); }); it('can forward to the original handler', async () => { protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true })); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { res.end('hello'); server.close(); }); const { url } = await listen(server); await contents.loadURL(url); expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello'); }); it('supports sniffing mime type', async () => { protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const server = http.createServer((req, res) => { if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); } }); const { url } = await listen(server); defer(() => server.close()); { await contents.loadURL(url); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.match(/white-space: pre-wrap/); } { await contents.loadURL(url + '?html'); const doc = await contents.executeJavaScript('document.documentElement.outerHTML'); expect(doc).to.equal('<html><head></head><body>hi</body></html>'); } }); // TODO(nornagon): this test doesn't pass on Linux currently, investigate. ifit(process.platform !== 'linux')('is fast', async () => { // 128 MB of spaces. const chunk = new Uint8Array(128 * 1024 * 1024); chunk.fill(' '.charCodeAt(0)); const server = http.createServer((req, res) => { // The sniffed mime type for the space-filled chunk will be // text/plain, which chews up all its performance in the renderer // trying to wrap lines. Setting content-type to text/html measures // something closer to just the raw cost of getting the bytes over // the wire. res.setHeader('content-type', 'text/html'); res.end(chunk); }); defer(() => server.close()); const { url } = await listen(server); const rawTime = await (async () => { await contents.loadURL(url); // warm const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); // Fetching through an intercepted handler should not be too much slower // than it would be if the protocol hadn't been intercepted. protocol.handle('http', async (req) => { return net.fetch(req, { bypassCustomProtocolHandlers: true }); }); defer(() => { protocol.unhandle('http'); }); const interceptedTime = await (async () => { const begin = Date.now(); await contents.loadURL(url); const end = Date.now(); return end - begin; })(); expect(interceptedTime).to.be.lessThan(rawTime * 1.5); }); }); });
closed
electron/electron
https://github.com/electron/electron
39,033
[Bug]: `BrowserWindow.moveAbove()` does not work with child windows
### 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 26.0.0-beta.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.4.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior Calling `BrowserWindow.moveAbove()` on a child window can move it above another child window. ### Actual Behavior The window is not moved. ### Testcase Gist URL https://gist.github.com/ddae3d8489b8efeb9f0963d70eea7838 ### Additional Information _No response_
https://github.com/electron/electron/issues/39033
https://github.com/electron/electron/pull/39034
9d1a16b2e62cf5838ecd1aeaf195952bb0a83f47
da3475998f154c19d3102c26fec175b9dd4eecec
2023-07-10T08:39:07Z
c++
2023-07-12T15:42:24Z
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/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/browser.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 != NSProgressIndicatorStyleBar) 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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); // 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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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::ShowAllTabs() { [window_ toggleTabOverview: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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
39,033
[Bug]: `BrowserWindow.moveAbove()` does not work with child windows
### 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 26.0.0-beta.2 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.4.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version N/A ### Expected Behavior Calling `BrowserWindow.moveAbove()` on a child window can move it above another child window. ### Actual Behavior The window is not moved. ### Testcase Gist URL https://gist.github.com/ddae3d8489b8efeb9f0963d70eea7838 ### Additional Information _No response_
https://github.com/electron/electron/issues/39033
https://github.com/electron/electron/pull/39034
9d1a16b2e62cf5838ecd1aeaf195952bb0a83f47
da3475998f154c19d3102c26fec175b9dd4eecec
2023-07-10T08:39:07Z
c++
2023-07-12T15:42:24Z
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/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/browser.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 != NSProgressIndicatorStyleBar) 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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); // 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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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::ShowAllTabs() { [window_ toggleTabOverview: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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
39,055
[Bug]: 26.0.0-beta.3 clipboard.readImage causes error RAW Bad optional access
### 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 26.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.2.0 ### Expected Behavior Not to crash ### Actual Behavior Running clipboard.readImage() completely crashes the app ### Testcase Gist URL https://gist.github.com/johnlindquist/db52bd78f76afc33366241ccf3d0cb2a ### Additional Information Make sure to have an image in the clipboard or else it won't crash.
https://github.com/electron/electron/issues/39055
https://github.com/electron/electron/pull/39069
34e7c3696a1375080197ebc68c222d221fbc2ef3
f61425efdb1357795a2c05a80923e2064158002b
2023-07-11T16:59:03Z
c++
2023-07-13T20:59:14Z
shell/common/api/electron_api_clipboard.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_clipboard.h" #include <map> #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPixmap.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/codec/png_codec.h" namespace electron::api { ui::ClipboardBuffer Clipboard::GetClipboardBuffer(gin_helper::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::ClipboardBuffer::kSelection; else return ui::ClipboardBuffer::kCopyPaste; } std::vector<std::u16string> Clipboard::AvailableFormats( gin_helper::Arguments* args) { std::vector<std::u16string> format_types; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardBuffer(args), /* data_dst = */ nullptr, &format_types); return format_types; } bool Clipboard::Has(const std::string& format_string, gin_helper::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::ClipboardFormatType format( ui::ClipboardFormatType::GetType(format_string)); if (format.GetName().empty()) format = ui::ClipboardFormatType::CustomPlatformType(format_string); return clipboard->IsFormatAvailable(format, GetClipboardBuffer(args), /* data_dst = */ nullptr); } std::string Clipboard::Read(const std::string& format_string) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); // Prefer raw platform format names ui::ClipboardFormatType rawFormat( ui::ClipboardFormatType::CustomPlatformType(format_string)); bool rawFormatAvailable = clipboard->IsFormatAvailable( rawFormat, ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr); #if BUILDFLAG(IS_LINUX) if (!rawFormatAvailable) { rawFormatAvailable = clipboard->IsFormatAvailable( rawFormat, ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr); } #endif if (rawFormatAvailable) { std::string data; clipboard->ReadData(rawFormat, /* data_dst = */ nullptr, &data); return data; } // Otherwise, resolve custom format names std::map<std::string, std::string> custom_format_names; custom_format_names = clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr); #if BUILDFLAG(IS_LINUX) if (!base::Contains(custom_format_names, format_string)) { custom_format_names = clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr); } #endif ui::ClipboardFormatType format; if (base::Contains(custom_format_names, format_string)) { format = ui::ClipboardFormatType(ui::ClipboardFormatType::CustomPlatformType( custom_format_names[format_string])); } else { format = ui::ClipboardFormatType( ui::ClipboardFormatType::CustomPlatformType(format_string)); } std::string data; clipboard->ReadData(format, /* data_dst = */ nullptr, &data); return data; } v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string, gin_helper::Arguments* args) { std::string data = Read(format_string); return node::Buffer::Copy(args->isolate(), data.data(), data.length()) .ToLocalChecked(); } void Clipboard::WriteBuffer(const std::string& format, const v8::Local<v8::Value> buffer, gin_helper::Arguments* args) { if (!node::Buffer::HasInstance(buffer)) { args->ThrowError("buffer must be a node Buffer"); return; } ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); base::span<const uint8_t> payload_span( reinterpret_cast<const uint8_t*>(node::Buffer::Data(buffer)), node::Buffer::Length(buffer)); writer.WriteUnsafeRawData(base::UTF8ToUTF16(format), mojo_base::BigBuffer(payload_span)); } void Clipboard::Write(const gin_helper::Dictionary& data, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); std::u16string text, html, bookmark; gfx::Image image; if (data.Get("text", &text)) { writer.WriteText(text); if (data.Get("bookmark", &bookmark)) writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text)); } if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string(), ui::ClipboardContentType::kSanitized); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } std::u16string Clipboard::ReadText(gin_helper::Arguments* args) { std::u16string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardBuffer(args); if (clipboard->IsFormatAvailable(ui::ClipboardFormatType::PlainTextType(), type, /* data_dst = */ nullptr)) { clipboard->ReadText(type, /* data_dst = */ nullptr, &data); } else { #if BUILDFLAG(IS_WIN) if (clipboard->IsFormatAvailable(ui::ClipboardFormatType::PlainTextAType(), type, /* data_dst = */ nullptr)) { std::string result; clipboard->ReadAsciiText(type, /* data_dst = */ nullptr, &result); data = base::ASCIIToUTF16(result); } #endif } return data; } void Clipboard::WriteText(const std::u16string& text, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteText(text); } std::u16string Clipboard::ReadRTF(gin_helper::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardBuffer(args), /* data_dst = */ nullptr, &data); return base::UTF8ToUTF16(data); } void Clipboard::WriteRTF(const std::string& text, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteRTF(text); } std::u16string Clipboard::ReadHTML(gin_helper::Arguments* args) { std::u16string data; std::u16string html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardBuffer(args), /* data_dst = */ nullptr, &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void Clipboard::WriteHTML(const std::u16string& html, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteHTML(html, std::string(), ui::ClipboardContentType::kSanitized); } v8::Local<v8::Value> Clipboard::ReadBookmark(gin_helper::Arguments* args) { std::u16string title; std::string url; gin_helper::Dictionary dict = gin_helper::Dictionary::CreateEmpty(args->isolate()); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadBookmark(/* data_dst = */ nullptr, &title, &url); dict.Set("title", title); dict.Set("url", url); return dict.GetHandle(); } void Clipboard::WriteBookmark(const std::u16string& title, const std::string& url, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteBookmark(title, url); } gfx::Image Clipboard::ReadImage(gin_helper::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); absl::optional<gfx::Image> image; clipboard->ReadPng( GetClipboardBuffer(args), /* data_dst = */ nullptr, base::BindOnce( [](absl::optional<gfx::Image>* image, const std::vector<uint8_t>& result) { SkBitmap bitmap; gfx::PNGCodec::Decode(result.data(), result.size(), &bitmap); image->emplace(gfx::Image::CreateFrom1xBitmap(bitmap)); }, &image)); DCHECK(image.has_value()); return image.value(); } void Clipboard::WriteImage(const gfx::Image& image, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); SkBitmap orig = image.AsBitmap(); SkBitmap bmp; if (bmp.tryAllocPixels(orig.info()) && orig.readPixels(bmp.info(), bmp.getPixels(), bmp.rowBytes(), 0, 0)) { writer.WriteImage(bmp); } } #if !BUILDFLAG(IS_MAC) void Clipboard::WriteFindText(const std::u16string& text) {} std::u16string Clipboard::ReadFindText() { return std::u16string(); } #endif void Clipboard::Clear(gin_helper::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardBuffer(args)); } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &electron::api::Clipboard::AvailableFormats); dict.SetMethod("has", &electron::api::Clipboard::Has); dict.SetMethod("read", &electron::api::Clipboard::Read); dict.SetMethod("write", &electron::api::Clipboard::Write); dict.SetMethod("readText", &electron::api::Clipboard::ReadText); dict.SetMethod("writeText", &electron::api::Clipboard::WriteText); dict.SetMethod("readRTF", &electron::api::Clipboard::ReadRTF); dict.SetMethod("writeRTF", &electron::api::Clipboard::WriteRTF); dict.SetMethod("readHTML", &electron::api::Clipboard::ReadHTML); dict.SetMethod("writeHTML", &electron::api::Clipboard::WriteHTML); dict.SetMethod("readBookmark", &electron::api::Clipboard::ReadBookmark); dict.SetMethod("writeBookmark", &electron::api::Clipboard::WriteBookmark); dict.SetMethod("readImage", &electron::api::Clipboard::ReadImage); dict.SetMethod("writeImage", &electron::api::Clipboard::WriteImage); dict.SetMethod("readFindText", &electron::api::Clipboard::ReadFindText); dict.SetMethod("writeFindText", &electron::api::Clipboard::WriteFindText); dict.SetMethod("readBuffer", &electron::api::Clipboard::ReadBuffer); dict.SetMethod("writeBuffer", &electron::api::Clipboard::WriteBuffer); dict.SetMethod("clear", &electron::api::Clipboard::Clear); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_common_clipboard, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,055
[Bug]: 26.0.0-beta.3 clipboard.readImage causes error RAW Bad optional access
### 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 26.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 25.2.0 ### Expected Behavior Not to crash ### Actual Behavior Running clipboard.readImage() completely crashes the app ### Testcase Gist URL https://gist.github.com/johnlindquist/db52bd78f76afc33366241ccf3d0cb2a ### Additional Information Make sure to have an image in the clipboard or else it won't crash.
https://github.com/electron/electron/issues/39055
https://github.com/electron/electron/pull/39069
34e7c3696a1375080197ebc68c222d221fbc2ef3
f61425efdb1357795a2c05a80923e2064158002b
2023-07-11T16:59:03Z
c++
2023-07-13T20:59:14Z
shell/common/api/electron_api_clipboard.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_clipboard.h" #include <map> #include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPixmap.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "ui/base/clipboard/scoped_clipboard_writer.h" #include "ui/gfx/codec/png_codec.h" namespace electron::api { ui::ClipboardBuffer Clipboard::GetClipboardBuffer(gin_helper::Arguments* args) { std::string type; if (args->GetNext(&type) && type == "selection") return ui::ClipboardBuffer::kSelection; else return ui::ClipboardBuffer::kCopyPaste; } std::vector<std::u16string> Clipboard::AvailableFormats( gin_helper::Arguments* args) { std::vector<std::u16string> format_types; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadAvailableTypes(GetClipboardBuffer(args), /* data_dst = */ nullptr, &format_types); return format_types; } bool Clipboard::Has(const std::string& format_string, gin_helper::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::ClipboardFormatType format( ui::ClipboardFormatType::GetType(format_string)); if (format.GetName().empty()) format = ui::ClipboardFormatType::CustomPlatformType(format_string); return clipboard->IsFormatAvailable(format, GetClipboardBuffer(args), /* data_dst = */ nullptr); } std::string Clipboard::Read(const std::string& format_string) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); // Prefer raw platform format names ui::ClipboardFormatType rawFormat( ui::ClipboardFormatType::CustomPlatformType(format_string)); bool rawFormatAvailable = clipboard->IsFormatAvailable( rawFormat, ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr); #if BUILDFLAG(IS_LINUX) if (!rawFormatAvailable) { rawFormatAvailable = clipboard->IsFormatAvailable( rawFormat, ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr); } #endif if (rawFormatAvailable) { std::string data; clipboard->ReadData(rawFormat, /* data_dst = */ nullptr, &data); return data; } // Otherwise, resolve custom format names std::map<std::string, std::string> custom_format_names; custom_format_names = clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr); #if BUILDFLAG(IS_LINUX) if (!base::Contains(custom_format_names, format_string)) { custom_format_names = clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr); } #endif ui::ClipboardFormatType format; if (base::Contains(custom_format_names, format_string)) { format = ui::ClipboardFormatType(ui::ClipboardFormatType::CustomPlatformType( custom_format_names[format_string])); } else { format = ui::ClipboardFormatType( ui::ClipboardFormatType::CustomPlatformType(format_string)); } std::string data; clipboard->ReadData(format, /* data_dst = */ nullptr, &data); return data; } v8::Local<v8::Value> Clipboard::ReadBuffer(const std::string& format_string, gin_helper::Arguments* args) { std::string data = Read(format_string); return node::Buffer::Copy(args->isolate(), data.data(), data.length()) .ToLocalChecked(); } void Clipboard::WriteBuffer(const std::string& format, const v8::Local<v8::Value> buffer, gin_helper::Arguments* args) { if (!node::Buffer::HasInstance(buffer)) { args->ThrowError("buffer must be a node Buffer"); return; } ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); base::span<const uint8_t> payload_span( reinterpret_cast<const uint8_t*>(node::Buffer::Data(buffer)), node::Buffer::Length(buffer)); writer.WriteUnsafeRawData(base::UTF8ToUTF16(format), mojo_base::BigBuffer(payload_span)); } void Clipboard::Write(const gin_helper::Dictionary& data, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); std::u16string text, html, bookmark; gfx::Image image; if (data.Get("text", &text)) { writer.WriteText(text); if (data.Get("bookmark", &bookmark)) writer.WriteBookmark(bookmark, base::UTF16ToUTF8(text)); } if (data.Get("rtf", &text)) { std::string rtf = base::UTF16ToUTF8(text); writer.WriteRTF(rtf); } if (data.Get("html", &html)) writer.WriteHTML(html, std::string(), ui::ClipboardContentType::kSanitized); if (data.Get("image", &image)) writer.WriteImage(image.AsBitmap()); } std::u16string Clipboard::ReadText(gin_helper::Arguments* args) { std::u16string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); auto type = GetClipboardBuffer(args); if (clipboard->IsFormatAvailable(ui::ClipboardFormatType::PlainTextType(), type, /* data_dst = */ nullptr)) { clipboard->ReadText(type, /* data_dst = */ nullptr, &data); } else { #if BUILDFLAG(IS_WIN) if (clipboard->IsFormatAvailable(ui::ClipboardFormatType::PlainTextAType(), type, /* data_dst = */ nullptr)) { std::string result; clipboard->ReadAsciiText(type, /* data_dst = */ nullptr, &result); data = base::ASCIIToUTF16(result); } #endif } return data; } void Clipboard::WriteText(const std::u16string& text, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteText(text); } std::u16string Clipboard::ReadRTF(gin_helper::Arguments* args) { std::string data; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadRTF(GetClipboardBuffer(args), /* data_dst = */ nullptr, &data); return base::UTF8ToUTF16(data); } void Clipboard::WriteRTF(const std::string& text, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteRTF(text); } std::u16string Clipboard::ReadHTML(gin_helper::Arguments* args) { std::u16string data; std::u16string html; std::string url; uint32_t start; uint32_t end; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadHTML(GetClipboardBuffer(args), /* data_dst = */ nullptr, &html, &url, &start, &end); data = html.substr(start, end - start); return data; } void Clipboard::WriteHTML(const std::u16string& html, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteHTML(html, std::string(), ui::ClipboardContentType::kSanitized); } v8::Local<v8::Value> Clipboard::ReadBookmark(gin_helper::Arguments* args) { std::u16string title; std::string url; gin_helper::Dictionary dict = gin_helper::Dictionary::CreateEmpty(args->isolate()); ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); clipboard->ReadBookmark(/* data_dst = */ nullptr, &title, &url); dict.Set("title", title); dict.Set("url", url); return dict.GetHandle(); } void Clipboard::WriteBookmark(const std::u16string& title, const std::string& url, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); writer.WriteBookmark(title, url); } gfx::Image Clipboard::ReadImage(gin_helper::Arguments* args) { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); absl::optional<gfx::Image> image; clipboard->ReadPng( GetClipboardBuffer(args), /* data_dst = */ nullptr, base::BindOnce( [](absl::optional<gfx::Image>* image, const std::vector<uint8_t>& result) { SkBitmap bitmap; gfx::PNGCodec::Decode(result.data(), result.size(), &bitmap); image->emplace(gfx::Image::CreateFrom1xBitmap(bitmap)); }, &image)); DCHECK(image.has_value()); return image.value(); } void Clipboard::WriteImage(const gfx::Image& image, gin_helper::Arguments* args) { ui::ScopedClipboardWriter writer(GetClipboardBuffer(args)); SkBitmap orig = image.AsBitmap(); SkBitmap bmp; if (bmp.tryAllocPixels(orig.info()) && orig.readPixels(bmp.info(), bmp.getPixels(), bmp.rowBytes(), 0, 0)) { writer.WriteImage(bmp); } } #if !BUILDFLAG(IS_MAC) void Clipboard::WriteFindText(const std::u16string& text) {} std::u16string Clipboard::ReadFindText() { return std::u16string(); } #endif void Clipboard::Clear(gin_helper::Arguments* args) { ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardBuffer(args)); } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("availableFormats", &electron::api::Clipboard::AvailableFormats); dict.SetMethod("has", &electron::api::Clipboard::Has); dict.SetMethod("read", &electron::api::Clipboard::Read); dict.SetMethod("write", &electron::api::Clipboard::Write); dict.SetMethod("readText", &electron::api::Clipboard::ReadText); dict.SetMethod("writeText", &electron::api::Clipboard::WriteText); dict.SetMethod("readRTF", &electron::api::Clipboard::ReadRTF); dict.SetMethod("writeRTF", &electron::api::Clipboard::WriteRTF); dict.SetMethod("readHTML", &electron::api::Clipboard::ReadHTML); dict.SetMethod("writeHTML", &electron::api::Clipboard::WriteHTML); dict.SetMethod("readBookmark", &electron::api::Clipboard::ReadBookmark); dict.SetMethod("writeBookmark", &electron::api::Clipboard::WriteBookmark); dict.SetMethod("readImage", &electron::api::Clipboard::ReadImage); dict.SetMethod("writeImage", &electron::api::Clipboard::WriteImage); dict.SetMethod("readFindText", &electron::api::Clipboard::ReadFindText); dict.SetMethod("writeFindText", &electron::api::Clipboard::WriteFindText); dict.SetMethod("readBuffer", &electron::api::Clipboard::ReadBuffer); dict.SetMethod("writeBuffer", &electron::api::Clipboard::WriteBuffer); dict.SetMethod("clear", &electron::api::Clipboard::Clear); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_common_clipboard, Initialize)
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
patches/chromium/fix_harden_blink_scriptstate_maybefrom.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Wed, 28 Jun 2023 21:11:40 +0900 Subject: fix: harden blink::ScriptState::MaybeFrom This is needed as side effect of https://chromium-review.googlesource.com/c/chromium/src/+/4609446 which now gets blink::ExecutionContext from blink::ScriptState and there are isolate callbacks which get entered from Node.js environment that has v8::Context not associated with blink::ScriptState. Some examples are ModifyCodeGenerationFromStrings in node_bindings.cc, blink::UseCounterCallback etc. Without this patch when blink::ScriptState::MaybeFrom tries to extract blink::ScriptState from the provided v8::Context and since Node.js has context embedder data fields with index greater than blink (see node_context_data.h) leading to the following CHECK failure. ``` script_state.h(169)] Security Check Failed: script_state ``` This patch adds a new tag in the context associated with ScriptState to uniquely identify. It is based on what Node.js does to identify the context created by it in `node_context_data.h`. PS: We are not performing a check like ``` ScriptState* script_state = static_cast<ScriptState*>(context->GetAlignedPointerFromEmbedderData( kV8ContextPerContextDataIndex)); if (!script_state) { return nullptr; } ``` since in 32-bit builds which does not have v8 sandbox enabled unlike 64-bit builds, the embedder data slot will not lazy initialize indexes in the former. This means accessing uninitialized lower indexes can return garbage values that cannot be null checked. Refer to v8::EmbedderDataSlot::store_aligned_pointer for context. diff --git a/gin/public/gin_embedders.h b/gin/public/gin_embedders.h index 8d7c5631fd8f1499c67384286f0e3c4037673b32..6a7491bc27334f6d1b1175eaa472c888e2b35b5e 100644 --- a/gin/public/gin_embedders.h +++ b/gin/public/gin_embedders.h @@ -18,6 +18,7 @@ namespace gin { enum GinEmbedder : uint16_t { kEmbedderNativeGin, kEmbedderBlink, + kEmbedderBlinkTag, kEmbedderPDFium, kEmbedderFuchsia, }; diff --git a/third_party/blink/renderer/platform/bindings/script_state.cc b/third_party/blink/renderer/platform/bindings/script_state.cc index 7ff8785cd64c1264a88f91f7bd3292c6943f58ea..bc14ad8cab9fa3ec45bcb9f670b198970ecbeb92 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.cc +++ b/third_party/blink/renderer/platform/bindings/script_state.cc @@ -13,6 +13,10 @@ namespace blink { ScriptState::CreateCallback ScriptState::s_create_callback_ = nullptr; +int const ScriptState::kScriptStateTag = 0x6e6f64; +void* const ScriptState::kScriptStateTagPtr = const_cast<void*>( + static_cast<const void*>(&ScriptState::kScriptStateTag)); + // static void ScriptState::SetCreateCallback(CreateCallback create_callback) { DCHECK(create_callback); @@ -37,6 +41,8 @@ ScriptState::ScriptState(v8::Local<v8::Context> context, DCHECK(world_); context_.SetWeak(this, &OnV8ContextCollectedCallback); context->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, this); + context->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, ScriptState::kScriptStateTagPtr); RendererResourceCoordinator::Get()->OnScriptStateCreated(this, execution_context); } @@ -78,6 +84,8 @@ void ScriptState::DissociateContext() { // Cut the reference from V8 context to ScriptState. GetContext()->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, nullptr); + GetContext()->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, nullptr); reference_from_v8_context_.Clear(); // Cut the reference from ScriptState to V8 context. diff --git a/third_party/blink/renderer/platform/bindings/script_state.h b/third_party/blink/renderer/platform/bindings/script_state.h index 7109852950cde0a6553000421faacefb39366b41..79be73cb660839d6074b11cd7491dc3d5e876345 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.h +++ b/third_party/blink/renderer/platform/bindings/script_state.h @@ -178,7 +178,12 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static ScriptState* MaybeFrom(v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); if (context->GetNumberOfEmbedderDataFields() <= - kV8ContextPerContextDataIndex) { + kV8ContextPerContextDataTagIndex) { + return nullptr; + } + if (context->GetAlignedPointerFromEmbedderData( + kV8ContextPerContextDataTagIndex) != + ScriptState::kScriptStateTagPtr) { return nullptr; } return From(context); @@ -249,9 +254,15 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static void SetCreateCallback(CreateCallback); friend class ScriptStateImpl; + static void* const kScriptStateTagPtr; + static int const kScriptStateTag; static constexpr int kV8ContextPerContextDataIndex = static_cast<int>(gin::kPerContextDataStartIndex) + static_cast<int>(gin::kEmbedderBlink); + static constexpr int kV8ContextPerContextDataTagIndex = + static_cast<int>(gin::kPerContextDataStartIndex) + + static_cast<int>(gin::kEmbedderBlink) + + static_cast<int>(gin::kEmbedderBlinkTag); }; // ScriptStateProtectingContext keeps the context associated with the
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedDebugOption(base::StringPiece option) { static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); return electron::fuses::IsNodeCliInspectEnabled() && options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (IsAllowedDebugOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #include <string> #include <type_traits> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "uv.h" // NOLINT(build/include_directory) #include "v8/include/v8.h" namespace base { class SingleThreadTaskRunner; } namespace node { class Environment; class MultiIsolatePlatform; class IsolateData; } // namespace node namespace electron { // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before // memory is released. Moreover, the memory can only be released in // close_cb or after it has returned." This class encapsulates the work // needed to follow those requirements. template <typename T, typename std::enable_if< // these are the C-style 'subclasses' of uv_handle_t std::is_same<T, uv_async_t>::value || std::is_same<T, uv_check_t>::value || std::is_same<T, uv_fs_event_t>::value || std::is_same<T, uv_fs_poll_t>::value || std::is_same<T, uv_idle_t>::value || std::is_same<T, uv_pipe_t>::value || std::is_same<T, uv_poll_t>::value || std::is_same<T, uv_prepare_t>::value || std::is_same<T, uv_process_t>::value || std::is_same<T, uv_signal_t>::value || std::is_same<T, uv_stream_t>::value || std::is_same<T, uv_tcp_t>::value || std::is_same<T, uv_timer_t>::value || std::is_same<T, uv_tty_t>::value || std::is_same<T, uv_udp_t>::value>::type* = nullptr> class UvHandle { public: UvHandle() : t_(new T) {} ~UvHandle() { reset(); } T* get() { return t_; } uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); } void reset() { auto* h = handle(); if (h != nullptr) { DCHECK_EQ(0, uv_is_closing(h)); uv_close(h, OnClosed); t_ = nullptr; } } private: static void OnClosed(uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); } RAW_PTR_EXCLUSION T* t_ = {}; }; class NodeBindings { public: enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker }; static NodeBindings* Create(BrowserEnvironment browser_env); static void RegisterBuiltinBindings(); static bool IsInitialized(); virtual ~NodeBindings(); // Setup V8, libuv. void Initialize(v8::Local<v8::Context> context); void SetNodeCliFlags(); // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args); node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); // Prepare embed thread for message loop integration. void PrepareEmbedThread(); // Notify embed thread to start polling after environment is loaded. void StartPolling(); // Gets/sets the per isolate data. void set_isolate_data(node::IsolateData* isolate_data) { isolate_data_ = isolate_data; } node::IsolateData* isolate_data() const { return isolate_data_; } // Gets/sets the environment to wrap uv loop. void set_uv_env(node::Environment* env) { uv_env_ = env; } node::Environment* uv_env() const { return uv_env_; } uv_loop_t* uv_loop() const { return uv_loop_; } bool in_worker_loop() const { return uv_loop_ == &worker_loop_; } // disable copy NodeBindings(const NodeBindings&) = delete; NodeBindings& operator=(const NodeBindings&) = delete; protected: explicit NodeBindings(BrowserEnvironment browser_env); // Called to poll events in new thread. virtual void PollEvents() = 0; // Run the libuv loop for once. void UvRunOnce(); // Make the main thread run libuv loop. void WakeupMainThread(); // Interrupt the PollEvents. void WakeupEmbedThread(); // Which environment we are running. const BrowserEnvironment browser_env_; // Current thread's MessageLoop. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Current thread's libuv loop. raw_ptr<uv_loop_t> uv_loop_; private: // Thread to poll uv events. static void EmbedThreadRunner(void* arg); // Indicates whether polling thread has been created. bool initialized_ = false; // Whether the libuv loop has ended. bool embed_closed_ = false; // Loop used when constructed in WORKER mode uv_loop_t worker_loop_; // Dummy handle to make uv's loop not quit. UvHandle<uv_async_t> dummy_uv_handle_; // Thread for polling events. uv_thread_t embed_thread_; // Semaphore to wait for main loop in the embed thread. uv_sem_t embed_sem_; // Environment that to wrap the uv loop. raw_ptr<node::Environment> uv_env_ = nullptr; // Isolate data used in creating the environment raw_ptr<node::IsolateData> isolate_data_ = nullptr; base::WeakPtrFactory<NodeBindings> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
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 "base/command_line.h" #include "base/containers/contains.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-with-error-code"; 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 (!base::Contains(injected_frames_, render_frame)) 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); return base::Contains(environments_, env) ? env : nullptr; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/renderer/web_worker_observer.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/renderer/web_worker_observer.h" #include <utility> #include "base/no_destructor.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" namespace electron { namespace { static base::NoDestructor<base::ThreadLocalOwnedPointer<WebWorkerObserver>> lazy_tls; } // namespace // static WebWorkerObserver* WebWorkerObserver::GetCurrent() { return lazy_tls->Get(); } // static WebWorkerObserver* WebWorkerObserver::Create() { auto obs = std::make_unique<WebWorkerObserver>(); auto* obs_raw = obs.get(); lazy_tls->Set(std::move(obs)); return obs_raw; } WebWorkerObserver::WebWorkerObserver() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kWorker)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} WebWorkerObserver::~WebWorkerObserver() { // 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` v8::MicrotaskQueue* microtask_queue = node_bindings_->uv_env()->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(node_bindings_->uv_env()); node::FreeIsolateData(node_bindings_->isolate_data()); microtask_queue->set_microtasks_policy(old_policy); } void WebWorkerObserver::WorkerScriptReadyForEvaluation( v8::Local<v8::Context> worker_context) { v8::Context::Scope context_scope(worker_context); auto* isolate = worker_context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, worker_context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Start the embed thread. 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(worker_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // 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 WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { node::Environment* env = node::Environment::GetCurrent(context); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); if (lazy_tls->Get()) lazy_tls->Set(nullptr); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
patches/chromium/fix_harden_blink_scriptstate_maybefrom.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Wed, 28 Jun 2023 21:11:40 +0900 Subject: fix: harden blink::ScriptState::MaybeFrom This is needed as side effect of https://chromium-review.googlesource.com/c/chromium/src/+/4609446 which now gets blink::ExecutionContext from blink::ScriptState and there are isolate callbacks which get entered from Node.js environment that has v8::Context not associated with blink::ScriptState. Some examples are ModifyCodeGenerationFromStrings in node_bindings.cc, blink::UseCounterCallback etc. Without this patch when blink::ScriptState::MaybeFrom tries to extract blink::ScriptState from the provided v8::Context and since Node.js has context embedder data fields with index greater than blink (see node_context_data.h) leading to the following CHECK failure. ``` script_state.h(169)] Security Check Failed: script_state ``` This patch adds a new tag in the context associated with ScriptState to uniquely identify. It is based on what Node.js does to identify the context created by it in `node_context_data.h`. PS: We are not performing a check like ``` ScriptState* script_state = static_cast<ScriptState*>(context->GetAlignedPointerFromEmbedderData( kV8ContextPerContextDataIndex)); if (!script_state) { return nullptr; } ``` since in 32-bit builds which does not have v8 sandbox enabled unlike 64-bit builds, the embedder data slot will not lazy initialize indexes in the former. This means accessing uninitialized lower indexes can return garbage values that cannot be null checked. Refer to v8::EmbedderDataSlot::store_aligned_pointer for context. diff --git a/gin/public/gin_embedders.h b/gin/public/gin_embedders.h index 8d7c5631fd8f1499c67384286f0e3c4037673b32..6a7491bc27334f6d1b1175eaa472c888e2b35b5e 100644 --- a/gin/public/gin_embedders.h +++ b/gin/public/gin_embedders.h @@ -18,6 +18,7 @@ namespace gin { enum GinEmbedder : uint16_t { kEmbedderNativeGin, kEmbedderBlink, + kEmbedderBlinkTag, kEmbedderPDFium, kEmbedderFuchsia, }; diff --git a/third_party/blink/renderer/platform/bindings/script_state.cc b/third_party/blink/renderer/platform/bindings/script_state.cc index 7ff8785cd64c1264a88f91f7bd3292c6943f58ea..bc14ad8cab9fa3ec45bcb9f670b198970ecbeb92 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.cc +++ b/third_party/blink/renderer/platform/bindings/script_state.cc @@ -13,6 +13,10 @@ namespace blink { ScriptState::CreateCallback ScriptState::s_create_callback_ = nullptr; +int const ScriptState::kScriptStateTag = 0x6e6f64; +void* const ScriptState::kScriptStateTagPtr = const_cast<void*>( + static_cast<const void*>(&ScriptState::kScriptStateTag)); + // static void ScriptState::SetCreateCallback(CreateCallback create_callback) { DCHECK(create_callback); @@ -37,6 +41,8 @@ ScriptState::ScriptState(v8::Local<v8::Context> context, DCHECK(world_); context_.SetWeak(this, &OnV8ContextCollectedCallback); context->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, this); + context->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, ScriptState::kScriptStateTagPtr); RendererResourceCoordinator::Get()->OnScriptStateCreated(this, execution_context); } @@ -78,6 +84,8 @@ void ScriptState::DissociateContext() { // Cut the reference from V8 context to ScriptState. GetContext()->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, nullptr); + GetContext()->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, nullptr); reference_from_v8_context_.Clear(); // Cut the reference from ScriptState to V8 context. diff --git a/third_party/blink/renderer/platform/bindings/script_state.h b/third_party/blink/renderer/platform/bindings/script_state.h index 7109852950cde0a6553000421faacefb39366b41..79be73cb660839d6074b11cd7491dc3d5e876345 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.h +++ b/third_party/blink/renderer/platform/bindings/script_state.h @@ -178,7 +178,12 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static ScriptState* MaybeFrom(v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); if (context->GetNumberOfEmbedderDataFields() <= - kV8ContextPerContextDataIndex) { + kV8ContextPerContextDataTagIndex) { + return nullptr; + } + if (context->GetAlignedPointerFromEmbedderData( + kV8ContextPerContextDataTagIndex) != + ScriptState::kScriptStateTagPtr) { return nullptr; } return From(context); @@ -249,9 +254,15 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static void SetCreateCallback(CreateCallback); friend class ScriptStateImpl; + static void* const kScriptStateTagPtr; + static int const kScriptStateTag; static constexpr int kV8ContextPerContextDataIndex = static_cast<int>(gin::kPerContextDataStartIndex) + static_cast<int>(gin::kEmbedderBlink); + static constexpr int kV8ContextPerContextDataTagIndex = + static_cast<int>(gin::kPerContextDataStartIndex) + + static_cast<int>(gin::kEmbedderBlink) + + static_cast<int>(gin::kEmbedderBlinkTag); }; // ScriptStateProtectingContext keeps the context associated with the
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedDebugOption(base::StringPiece option) { static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); return electron::fuses::IsNodeCliInspectEnabled() && options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (IsAllowedDebugOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #include <string> #include <type_traits> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "uv.h" // NOLINT(build/include_directory) #include "v8/include/v8.h" namespace base { class SingleThreadTaskRunner; } namespace node { class Environment; class MultiIsolatePlatform; class IsolateData; } // namespace node namespace electron { // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before // memory is released. Moreover, the memory can only be released in // close_cb or after it has returned." This class encapsulates the work // needed to follow those requirements. template <typename T, typename std::enable_if< // these are the C-style 'subclasses' of uv_handle_t std::is_same<T, uv_async_t>::value || std::is_same<T, uv_check_t>::value || std::is_same<T, uv_fs_event_t>::value || std::is_same<T, uv_fs_poll_t>::value || std::is_same<T, uv_idle_t>::value || std::is_same<T, uv_pipe_t>::value || std::is_same<T, uv_poll_t>::value || std::is_same<T, uv_prepare_t>::value || std::is_same<T, uv_process_t>::value || std::is_same<T, uv_signal_t>::value || std::is_same<T, uv_stream_t>::value || std::is_same<T, uv_tcp_t>::value || std::is_same<T, uv_timer_t>::value || std::is_same<T, uv_tty_t>::value || std::is_same<T, uv_udp_t>::value>::type* = nullptr> class UvHandle { public: UvHandle() : t_(new T) {} ~UvHandle() { reset(); } T* get() { return t_; } uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); } void reset() { auto* h = handle(); if (h != nullptr) { DCHECK_EQ(0, uv_is_closing(h)); uv_close(h, OnClosed); t_ = nullptr; } } private: static void OnClosed(uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); } RAW_PTR_EXCLUSION T* t_ = {}; }; class NodeBindings { public: enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker }; static NodeBindings* Create(BrowserEnvironment browser_env); static void RegisterBuiltinBindings(); static bool IsInitialized(); virtual ~NodeBindings(); // Setup V8, libuv. void Initialize(v8::Local<v8::Context> context); void SetNodeCliFlags(); // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args); node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); // Prepare embed thread for message loop integration. void PrepareEmbedThread(); // Notify embed thread to start polling after environment is loaded. void StartPolling(); // Gets/sets the per isolate data. void set_isolate_data(node::IsolateData* isolate_data) { isolate_data_ = isolate_data; } node::IsolateData* isolate_data() const { return isolate_data_; } // Gets/sets the environment to wrap uv loop. void set_uv_env(node::Environment* env) { uv_env_ = env; } node::Environment* uv_env() const { return uv_env_; } uv_loop_t* uv_loop() const { return uv_loop_; } bool in_worker_loop() const { return uv_loop_ == &worker_loop_; } // disable copy NodeBindings(const NodeBindings&) = delete; NodeBindings& operator=(const NodeBindings&) = delete; protected: explicit NodeBindings(BrowserEnvironment browser_env); // Called to poll events in new thread. virtual void PollEvents() = 0; // Run the libuv loop for once. void UvRunOnce(); // Make the main thread run libuv loop. void WakeupMainThread(); // Interrupt the PollEvents. void WakeupEmbedThread(); // Which environment we are running. const BrowserEnvironment browser_env_; // Current thread's MessageLoop. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Current thread's libuv loop. raw_ptr<uv_loop_t> uv_loop_; private: // Thread to poll uv events. static void EmbedThreadRunner(void* arg); // Indicates whether polling thread has been created. bool initialized_ = false; // Whether the libuv loop has ended. bool embed_closed_ = false; // Loop used when constructed in WORKER mode uv_loop_t worker_loop_; // Dummy handle to make uv's loop not quit. UvHandle<uv_async_t> dummy_uv_handle_; // Thread for polling events. uv_thread_t embed_thread_; // Semaphore to wait for main loop in the embed thread. uv_sem_t embed_sem_; // Environment that to wrap the uv loop. raw_ptr<node::Environment> uv_env_ = nullptr; // Isolate data used in creating the environment raw_ptr<node::IsolateData> isolate_data_ = nullptr; base::WeakPtrFactory<NodeBindings> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
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 "base/command_line.h" #include "base/containers/contains.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-with-error-code"; 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 (!base::Contains(injected_frames_, render_frame)) 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); return base::Contains(environments_, env) ? env : nullptr; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
shell/renderer/web_worker_observer.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/renderer/web_worker_observer.h" #include <utility> #include "base/no_destructor.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" namespace electron { namespace { static base::NoDestructor<base::ThreadLocalOwnedPointer<WebWorkerObserver>> lazy_tls; } // namespace // static WebWorkerObserver* WebWorkerObserver::GetCurrent() { return lazy_tls->Get(); } // static WebWorkerObserver* WebWorkerObserver::Create() { auto obs = std::make_unique<WebWorkerObserver>(); auto* obs_raw = obs.get(); lazy_tls->Set(std::move(obs)); return obs_raw; } WebWorkerObserver::WebWorkerObserver() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kWorker)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} WebWorkerObserver::~WebWorkerObserver() { // 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` v8::MicrotaskQueue* microtask_queue = node_bindings_->uv_env()->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(node_bindings_->uv_env()); node::FreeIsolateData(node_bindings_->isolate_data()); microtask_queue->set_microtasks_policy(old_policy); } void WebWorkerObserver::WorkerScriptReadyForEvaluation( v8::Local<v8::Context> worker_context) { v8::Context::Scope context_scope(worker_context); auto* isolate = worker_context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, worker_context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Start the embed thread. 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(worker_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // 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 WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { node::Environment* env = node::Environment::GetCurrent(context); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); if (lazy_tls->Get()) lazy_tls->Set(nullptr); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
36,858
[Bug]: Uncaught illegal state exception and renderer crash with node immediates and closing child window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.x, 17.x, 22.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 (22621.963) ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior Closing a child window should not produce an 'Uncaught illegal state' exception. Furthermore, it shouldn't cause the renderer process to exit with code 7 (which can specifically occur if there is a node native immediate being used, see additional information below). ### Actual Behavior A race condition can occur when using `setImmediate` (or using a node module that sets up native immediates) in a node environment and closing a child window that has a separate node environment (but shares the underlying isolate and event loop). Note: This seems to occur when the BrowserWindow webPreferences sandbox is set to false. The behavior here is that the console will report `Uncaught illegal state` and in certain cases the renderer process will simply exit with code 7. The following was also reported to stderr: ``` illegal access (Use `electron --trace-uncaught ...` to show where the exception was thrown) ``` ### Testcase Gist URL https://gist.github.com/markh-discord/1bb303c57d1a20aeee95aeedbc403ab3 ### Additional Information Note: This seems to occur only when the main BrowserWindow webPreferences sandbox is set to false. The reproduce project in the gist may require a few attempts, but when clicking the button to open the window it will automatically close. Around 1-10 attempts may be needed to display the error in the console. To improve the simplicity of this I used Javascript `setImmediate` which seems to be more recoverable as it doesn't exit the process. In the steps below there is a node native immediate being setup by the node https module that does cause the renderer process to eventually exit. Reproduce steps aren't precise since this is a race condition, however the following path seems to hit this: 1. node `Environment A` is created and `Environment::InitializeLibuv` is run and sets up its `Environment::CheckImmediate` method in `uv_check_start`. a. This will be interesting later, but it's called via the event loop `uv_run`: https://github.com/libuv/libuv/blob/e972c6705f197e12d211b598fc514bbea051425d/src/win/core.c#L645 1. Window is opened, a new node Environment (I'll call `Environment B`) is created: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/renderer/electron_renderer_client.cc#L91-L92 a. This environment uses the existing `NodeBindings::isolate_data_`, which also shares the isolate and uv_loop_ from `Environment A`: https://github.com/electron/electron/blob/dfe501941cd9e7092829c3ef8e27e322047cf736/shell/common/node_bindings.cc#L493 2. node `Environment A` has a native immediate pushed from http post work being done by the node http module. a. This can occur in a few places via `env()->SetImmediate(...)`, here's one as an example: https://github.com/nodejs/node/blob/e8db11c5b2169931238db6c02f6d7f80b3c6e759/src/crypto/crypto_tls.cc#L593 3. Window is closed, causing `Environment B` to begin cleanup: a. `node::FreeEnvironment` is called, and sets up JS to be disallowed: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/api/environment.cc#L420-L421 b. `node::CleanupHandles` is eventually called, this starts up the event loop via `uv_run`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#LL966C21-L966C21 c. Per 1a above, the `uv_check_invoke` is called, and the `Environment A`'s `CheckImmediate` is run 4. At this point we're now running things from `Environment A`, in particular it will begin executing the native immediates that it has. Note that we're still in the same call stack and the isolate's state to disallow JS is still flagged. 5. Since a native immediate was added in step 2 above, this begins running, eventually for the http stream work it tries to callback into Javascript via `node::ReportWritesToJSStreamListener::OnStreamAfterReqFinished`: a. https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/stream_base.cc#L632 6. This then fails the check on if JS is allowed to be executed (setup on shared isolate from `Environment B` in step 3a): a. https://chromium.googlesource.com/v8/v8/+/roll/src/execution.cc ``` if (!ThrowOnJavascriptExecution::IsAllowed(isolate)) { isolate->ThrowIllegalOperation(); ``` 7. Call stack begins unwinding and eventually hits: `errors::TriggerUncaughtException`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1097 8. This in turn attempts to execute a `fatal_exception_function.As<Function>()->Call`: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1126-L1127 a. Since JS is still disallowed we get _another_ `v8::internal::Isolate::ThrowIllegalOperation` triggered 9. This unwinds and executes the `TryCatchScope` dtor setup in the above scope: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L1116-L1117 10. The `TryCatchScope::~TryCatchScope` then builds the message to dumps and eventually causes the `env_->Exit` to be called: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/node_errors.cc#L572 11. This then runs the `Environment::Exit` and eventually will exit the process: https://github.com/nodejs/node/blob/2af83ea0f8a1594c0d0bf4bc4b3035234bcd895e/src/env.cc#L1548
https://github.com/electron/electron/issues/36858
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-01-10T20:50:12Z
c++
2023-07-18T08:41:50Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
patches/chromium/fix_harden_blink_scriptstate_maybefrom.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Wed, 28 Jun 2023 21:11:40 +0900 Subject: fix: harden blink::ScriptState::MaybeFrom This is needed as side effect of https://chromium-review.googlesource.com/c/chromium/src/+/4609446 which now gets blink::ExecutionContext from blink::ScriptState and there are isolate callbacks which get entered from Node.js environment that has v8::Context not associated with blink::ScriptState. Some examples are ModifyCodeGenerationFromStrings in node_bindings.cc, blink::UseCounterCallback etc. Without this patch when blink::ScriptState::MaybeFrom tries to extract blink::ScriptState from the provided v8::Context and since Node.js has context embedder data fields with index greater than blink (see node_context_data.h) leading to the following CHECK failure. ``` script_state.h(169)] Security Check Failed: script_state ``` This patch adds a new tag in the context associated with ScriptState to uniquely identify. It is based on what Node.js does to identify the context created by it in `node_context_data.h`. PS: We are not performing a check like ``` ScriptState* script_state = static_cast<ScriptState*>(context->GetAlignedPointerFromEmbedderData( kV8ContextPerContextDataIndex)); if (!script_state) { return nullptr; } ``` since in 32-bit builds which does not have v8 sandbox enabled unlike 64-bit builds, the embedder data slot will not lazy initialize indexes in the former. This means accessing uninitialized lower indexes can return garbage values that cannot be null checked. Refer to v8::EmbedderDataSlot::store_aligned_pointer for context. diff --git a/gin/public/gin_embedders.h b/gin/public/gin_embedders.h index 8d7c5631fd8f1499c67384286f0e3c4037673b32..6a7491bc27334f6d1b1175eaa472c888e2b35b5e 100644 --- a/gin/public/gin_embedders.h +++ b/gin/public/gin_embedders.h @@ -18,6 +18,7 @@ namespace gin { enum GinEmbedder : uint16_t { kEmbedderNativeGin, kEmbedderBlink, + kEmbedderBlinkTag, kEmbedderPDFium, kEmbedderFuchsia, }; diff --git a/third_party/blink/renderer/platform/bindings/script_state.cc b/third_party/blink/renderer/platform/bindings/script_state.cc index 7ff8785cd64c1264a88f91f7bd3292c6943f58ea..bc14ad8cab9fa3ec45bcb9f670b198970ecbeb92 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.cc +++ b/third_party/blink/renderer/platform/bindings/script_state.cc @@ -13,6 +13,10 @@ namespace blink { ScriptState::CreateCallback ScriptState::s_create_callback_ = nullptr; +int const ScriptState::kScriptStateTag = 0x6e6f64; +void* const ScriptState::kScriptStateTagPtr = const_cast<void*>( + static_cast<const void*>(&ScriptState::kScriptStateTag)); + // static void ScriptState::SetCreateCallback(CreateCallback create_callback) { DCHECK(create_callback); @@ -37,6 +41,8 @@ ScriptState::ScriptState(v8::Local<v8::Context> context, DCHECK(world_); context_.SetWeak(this, &OnV8ContextCollectedCallback); context->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, this); + context->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, ScriptState::kScriptStateTagPtr); RendererResourceCoordinator::Get()->OnScriptStateCreated(this, execution_context); } @@ -78,6 +84,8 @@ void ScriptState::DissociateContext() { // Cut the reference from V8 context to ScriptState. GetContext()->SetAlignedPointerInEmbedderData(kV8ContextPerContextDataIndex, nullptr); + GetContext()->SetAlignedPointerInEmbedderData( + kV8ContextPerContextDataTagIndex, nullptr); reference_from_v8_context_.Clear(); // Cut the reference from ScriptState to V8 context. diff --git a/third_party/blink/renderer/platform/bindings/script_state.h b/third_party/blink/renderer/platform/bindings/script_state.h index 7109852950cde0a6553000421faacefb39366b41..79be73cb660839d6074b11cd7491dc3d5e876345 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.h +++ b/third_party/blink/renderer/platform/bindings/script_state.h @@ -178,7 +178,12 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static ScriptState* MaybeFrom(v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); if (context->GetNumberOfEmbedderDataFields() <= - kV8ContextPerContextDataIndex) { + kV8ContextPerContextDataTagIndex) { + return nullptr; + } + if (context->GetAlignedPointerFromEmbedderData( + kV8ContextPerContextDataTagIndex) != + ScriptState::kScriptStateTagPtr) { return nullptr; } return From(context); @@ -249,9 +254,15 @@ class PLATFORM_EXPORT ScriptState : public GarbageCollected<ScriptState> { static void SetCreateCallback(CreateCallback); friend class ScriptStateImpl; + static void* const kScriptStateTagPtr; + static int const kScriptStateTag; static constexpr int kV8ContextPerContextDataIndex = static_cast<int>(gin::kPerContextDataStartIndex) + static_cast<int>(gin::kEmbedderBlink); + static constexpr int kV8ContextPerContextDataTagIndex = + static_cast<int>(gin::kPerContextDataStartIndex) + + static_cast<int>(gin::kEmbedderBlink) + + static_cast<int>(gin::kEmbedderBlinkTag); }; // ScriptStateProtectingContext keeps the context associated with the
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/node_bindings.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/containers/fixed_flat_set.h" #include "base/environment.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_paths.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "shell/browser/api/electron_api_app.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/electron_command_line.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/gin_helper/locker.h" #include "shell/common/gin_helper/microtasks_scope.h" #include "shell/common/mac/main_application_bundle.h" #include "shell/common/node_includes.h" #include "third_party/blink/renderer/bindings/core/v8/v8_initializer.h" // nogncheck #include "third_party/electron_node/src/debug_utils.h" #if !IS_MAS_BUILD() #include "shell/common/crash_keys.h" #endif #define ELECTRON_BROWSER_BINDINGS(V) \ V(electron_browser_app) \ V(electron_browser_auto_updater) \ V(electron_browser_browser_view) \ V(electron_browser_content_tracing) \ V(electron_browser_crash_reporter) \ V(electron_browser_desktop_capturer) \ V(electron_browser_dialog) \ V(electron_browser_event_emitter) \ V(electron_browser_global_shortcut) \ V(electron_browser_in_app_purchase) \ V(electron_browser_menu) \ V(electron_browser_message_port) \ V(electron_browser_native_theme) \ V(electron_browser_net) \ V(electron_browser_notification) \ V(electron_browser_power_monitor) \ V(electron_browser_power_save_blocker) \ V(electron_browser_protocol) \ V(electron_browser_printing) \ V(electron_browser_push_notifications) \ V(electron_browser_safe_storage) \ V(electron_browser_session) \ V(electron_browser_screen) \ V(electron_browser_system_preferences) \ V(electron_browser_base_window) \ V(electron_browser_tray) \ V(electron_browser_utility_process) \ V(electron_browser_view) \ V(electron_browser_web_contents) \ V(electron_browser_web_contents_view) \ V(electron_browser_web_frame_main) \ V(electron_browser_web_view_manager) \ V(electron_browser_window) #define ELECTRON_COMMON_BINDINGS(V) \ V(electron_common_asar) \ V(electron_common_clipboard) \ V(electron_common_command_line) \ V(electron_common_crashpad_support) \ V(electron_common_environment) \ V(electron_common_features) \ V(electron_common_native_image) \ V(electron_common_shell) \ V(electron_common_v8_util) #define ELECTRON_RENDERER_BINDINGS(V) \ V(electron_renderer_context_bridge) \ V(electron_renderer_crash_reporter) \ V(electron_renderer_ipc) \ V(electron_renderer_web_frame) #define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port) #define ELECTRON_VIEWS_BINDINGS(V) V(electron_browser_image_view) #define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing) // This is used to load built-in bindings. Instead of using // __attribute__((constructor)), we call the _register_<modname> // function for each built-in bindings explicitly. This is only // forward declaration. The definitions are in each binding's // implementation when calling the NODE_LINKED_BINDING_CONTEXT_AWARE. #define V(modname) void _register_##modname(); ELECTRON_BROWSER_BINDINGS(V) ELECTRON_COMMON_BINDINGS(V) ELECTRON_RENDERER_BINDINGS(V) ELECTRON_UTILITY_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V namespace { void stop_and_close_uv_loop(uv_loop_t* loop) { uv_stop(loop); auto const ensure_closing = [](uv_handle_t* handle, void*) { // We should be using the UvHandle wrapper everywhere, in which case // all handles should already be in a closing state... DCHECK(uv_is_closing(handle)); // ...but if a raw handle got through, through, do the right thing anyway if (!uv_is_closing(handle)) { uv_close(handle, nullptr); } }; uv_walk(loop, ensure_closing, nullptr); // All remaining handles are in a closing state now. // Pump the event loop so that they can finish closing. for (;;) if (uv_run(loop, UV_RUN_DEFAULT) == 0) break; DCHECK_EQ(0, uv_loop_alive(loop)); node::CheckedUvLoopClose(loop); } bool g_is_initialized = false; void V8FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; #if !IS_MAS_BUILD() electron::crash_keys::SetCrashKey("electron.v8-fatal.message", message); electron::crash_keys::SetCrashKey("electron.v8-fatal.location", location); #endif volatile int* zero = nullptr; *zero = 0; } bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context, v8::Local<v8::String> source) { // If we're running with contextIsolation enabled in the renderer process, // fall back to Blink's logic. if (node::Environment::GetCurrent(context) == nullptr) { if (!electron::IsRendererProcess()) return false; return blink::V8Initializer::WasmCodeGenerationCheckCallbackInMainThread( context, source); } return node::AllowWasmCodeGenerationCallback(context, source); } v8::ModifyCodeGenerationFromStringsResult ModifyCodeGenerationFromStrings( v8::Local<v8::Context> context, v8::Local<v8::Value> source, bool is_code_like) { if (node::Environment::GetCurrent(context) == nullptr) { // No node environment means we're in the renderer process, either in a // sandboxed renderer or in an unsandboxed renderer with context isolation // enabled. if (!electron::IsRendererProcess()) { NOTREACHED(); return {false, {}}; } return blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); } // If we get here then we have a node environment, so either a) we're in the // non-rendrer process, or b) we're in the renderer process in a context that // has both node and blink, i.e. contextIsolation disabled. // If we're in the renderer with contextIsolation disabled, ask blink first // (for CSP), and iff that allows codegen, delegate to node. if (electron::IsRendererProcess()) { v8::ModifyCodeGenerationFromStringsResult result = blink::V8Initializer::CodeGenerationCheckCallbackInMainThread( context, source, is_code_like); if (!result.codegen_allowed) return result; } // If we're in the main process or utility process, delegate to node. return node::ModifyCodeGenerationFromStrings(context, source, is_code_like); } void ErrorMessageListener(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); node::Environment* env = node::Environment::GetCurrent(isolate); if (env) { gin_helper::MicrotasksScope microtasks_scope( isolate, env->context()->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Emit the after() hooks now that the exception has been handled. // Analogous to node/lib/internal/process/execution.js#L176-L180 if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) { while (env->async_hooks()->fields()[node::AsyncHooks::kStackLength]) { node::AsyncWrap::EmitAfter(env, env->execution_async_id()); env->async_hooks()->pop_async_context(env->execution_async_id()); } } // Ensure that the async id stack is properly cleared so the async // hook stack does not become corrupted. env->async_hooks()->clear_async_id_stack(); } } // Only allow DebugOptions in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. bool IsAllowedDebugOption(base::StringPiece option) { static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ "--debug", "--debug-brk", "--debug-port", "--inspect", "--inspect-brk", "--inspect-brk-node", "--inspect-port", "--inspect-publish-uid", }); return electron::fuses::IsNodeCliInspectEnabled() && options.contains(option); } // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ "--enable-fips", "--force-fips", "--openssl-config", "--use-bundled-ca", "--use-openssl-ca", }); static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ "--http-parser", "--max-http-header-size", }); if (env->HasVar("NODE_OPTIONS")) { if (electron::fuses::IsNodeOptionsEnabled()) { std::string options; env->GetVar("NODE_OPTIONS", &options); std::vector<std::string> parts = base::SplitString( options, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); bool is_packaged_app = electron::api::App::IsPackaged(); for (const auto& part : parts) { // Strip off values passed to individual NODE_OPTIONs std::string option = part.substr(0, part.find('=')); if (is_packaged_app && !pkg_opts.contains(option)) { // Explicitly disallow majority of NODE_OPTIONS in packaged apps LOG(ERROR) << "Most NODE_OPTIONs are not supported in packaged apps." << " See documentation for more details."; options.erase(options.find(option), part.length()); } else if (disallowed.contains(option)) { // Remove NODE_OPTIONS specifically disallowed for use in Node.js // through Electron owing to constraints like BoringSSL. LOG(ERROR) << "The NODE_OPTION " << option << " is not supported in Electron"; options.erase(options.find(option), part.length()); } } // overwrite new NODE_OPTIONS without unsupported variables env->SetVar("NODE_OPTIONS", options); } else { LOG(ERROR) << "NODE_OPTIONS have been disabled in this app"; env->SetVar("NODE_OPTIONS", ""); } } } } // namespace namespace electron { namespace { base::FilePath GetResourcesPath() { #if BUILDFLAG(IS_MAC) return MainApplicationBundlePath().Append("Contents").Append("Resources"); #else auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return exec_path.DirName().Append(FILE_PATH_LITERAL("resources")); #endif } } // namespace NodeBindings::NodeBindings(BrowserEnvironment browser_env) : browser_env_(browser_env) { if (browser_env == BrowserEnvironment::kWorker) { uv_loop_init(&worker_loop_); uv_loop_ = &worker_loop_; } else { uv_loop_ = uv_default_loop(); } // Interrupt embed polling when a handle is started. uv_loop_configure(uv_loop_, UV_LOOP_INTERRUPT_ON_IO_CHANGE); } NodeBindings::~NodeBindings() { // Quit the embed thread. embed_closed_ = true; uv_sem_post(&embed_sem_); WakeupEmbedThread(); // Wait for everything to be done. uv_thread_join(&embed_thread_); // Clear uv. uv_sem_destroy(&embed_sem_); dummy_uv_handle_.reset(); // Clean up worker loop if (in_worker_loop()) stop_and_close_uv_loop(uv_loop_); } void NodeBindings::RegisterBuiltinBindings() { #define V(modname) _register_##modname(); if (IsBrowserProcess()) { ELECTRON_BROWSER_BINDINGS(V) #if BUILDFLAG(ENABLE_VIEWS_API) ELECTRON_VIEWS_BINDINGS(V) #endif } ELECTRON_COMMON_BINDINGS(V) if (IsRendererProcess()) { ELECTRON_RENDERER_BINDINGS(V) } if (IsUtilityProcess()) { ELECTRON_UTILITY_BINDINGS(V) } #if DCHECK_IS_ON() ELECTRON_TESTING_BINDINGS(V) #endif #undef V } bool NodeBindings::IsInitialized() { return g_is_initialized; } // Initialize Node.js cli options to pass to Node.js // See https://nodejs.org/api/cli.html#cli_options void NodeBindings::SetNodeCliFlags() { const auto argv = base::CommandLine::ForCurrentProcess()->argv(); std::vector<std::string> args; // TODO(codebytere): We need to set the first entry in args to the // process name owing to src/node_options-inl.h#L286-L290 but this is // redundant and so should be refactored upstream. args.reserve(argv.size() + 1); args.emplace_back("electron"); for (const auto& arg : argv) { #if BUILDFLAG(IS_WIN) const auto& option = base::WideToUTF8(arg); #else const auto& option = arg; #endif const auto stripped = base::StringPiece(option).substr(0, option.find('=')); // Only allow in no-op (--) option or DebugOptions if (IsAllowedDebugOption(stripped) || stripped == "--") args.push_back(option); } // We need to disable Node.js' fetch implementation to prevent // conflict with Blink's in renderer and worker processes. if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { args.push_back("--no-experimental-fetch"); } std::vector<std::string> errors; const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, node::kDisallowedInEnvironment); const std::string err_str = "Error parsing Node.js cli flags "; if (exit_code != 0) { LOG(ERROR) << err_str; } else if (!errors.empty()) { LOG(ERROR) << err_str << base::JoinString(errors, " "); } } void NodeBindings::Initialize(v8::Local<v8::Context> context) { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. #if BUILDFLAG(IS_LINUX) // Get real command line in renderer process forked by zygote. if (browser_env_ != BrowserEnvironment::kBrowser) ElectronCommandLine::InitializeFromCommandLine(); #endif // Explicitly register electron's builtin bindings. RegisterBuiltinBindings(); // Parse and set Node.js cli flags. SetNodeCliFlags(); auto env = base::Environment::Create(); SetNodeOptions(env.get()); std::vector<std::string> argv = {"electron"}; std::vector<std::string> exec_argv; std::vector<std::string> errors; uint64_t process_flags = node::ProcessFlags::kNoFlags; // We do not want the child processes spawned from the utility process // to inherit the custom stdio handles created for the parent. if (browser_env_ != BrowserEnvironment::kUtility) process_flags |= node::ProcessFlags::kEnableStdioInheritance; if (!fuses::IsNodeOptionsEnabled()) process_flags |= node::ProcessFlags::kDisableNodeOptionsEnv; int exit_code = node::InitializeNodeWithArgs( &argv, &exec_argv, &errors, static_cast<node::ProcessFlags::Flags>(process_flags)); for (const std::string& error : errors) fprintf(stderr, "%s: %s\n", argv[0].c_str(), error.c_str()); if (exit_code != 0) exit(exit_code); #if BUILDFLAG(IS_WIN) // uv_init overrides error mode to suppress the default crash dialog, bring // it back if user wants to show it. if (browser_env_ == BrowserEnvironment::kBrowser || env->HasVar("ELECTRON_DEFAULT_ERROR_MODE")) SetErrorMode(GetErrorMode() & ~SEM_NOGPFAULTERRORBOX); #endif gin_helper::internal::Event::GetConstructor(context); g_is_initialized = true; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args) { // Feed node the path to initialization script. std::string process_type; switch (browser_env_) { case BrowserEnvironment::kBrowser: process_type = "browser"; break; case BrowserEnvironment::kRenderer: process_type = "renderer"; break; case BrowserEnvironment::kWorker: process_type = "worker"; break; case BrowserEnvironment::kUtility: process_type = "utility"; break; } v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", "default_app.asar"}; const std::vector<std::string> app_asar_search_paths = {"app.asar"}; context->Global()->SetPrivate( context, v8::Private::ForApi( isolate, gin::ConvertToV8(isolate, "appSearchPaths").As<v8::String>()), gin::ConvertToV8(isolate, electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); } base::FilePath resources_path = GetResourcesPath(); std::string init_script = "electron/js2c/" + process_type + "_init"; args.insert(args.begin() + 1, init_script); if (!isolate_data_) isolate_data_ = node::CreateIsolateData(isolate, uv_loop_, platform); node::Environment* env; uint64_t flags = node::EnvironmentFlags::kDefaultFlags | node::EnvironmentFlags::kHideConsoleWindows | node::EnvironmentFlags::kNoGlobalSearchPaths; if (browser_env_ == BrowserEnvironment::kRenderer || browser_env_ == BrowserEnvironment::kWorker) { // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. // We also avoid overriding globals like setImmediate, clearImmediate // queueMicrotask etc during the bootstrap phase of Node.js // for processes that already have these defined by DOM. // Check //third_party/electron_node/lib/internal/bootstrap/node.js // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } if (!electron::fuses::IsNodeCliInspectEnabled()) { // If --inspect and friends are disabled we also shouldn't listen for // SIGUSR1 flags |= node::EnvironmentFlags::kNoStartDebugSignalHandler; } { v8::TryCatch try_catch(isolate); env = node::CreateEnvironment( isolate_data_, context, args, exec_args, static_cast<node::EnvironmentFlags::Flags>(flags)); if (try_catch.HasCaught()) { std::string err_msg = "Failed to initialize node environment in process: " + process_type; v8::Local<v8::Message> message = try_catch.Message(); std::string msg; if (!message.IsEmpty() && gin::ConvertFromV8(isolate, message->Get(), &msg)) err_msg += " , with error: " + msg; LOG(ERROR) << err_msg; } } DCHECK(env); node::IsolateSettings is; // Use a custom fatal error callback to allow us to add // crash message and location to CrashReports. is.fatal_error_callback = V8FatalErrorCallback; // We don't want to abort either in the renderer or browser processes. // We already listen for uncaught exceptions and handle them there. // For utility process we expect the process to behave as standard // Node.js runtime and abort the process with appropriate exit // code depending on a handler being set for `uncaughtException` event. if (browser_env_ != BrowserEnvironment::kUtility) { is.should_abort_on_uncaught_exception_callback = [](v8::Isolate*) { return false; }; } // Use a custom callback here to allow us to leverage Blink's logic in the // renderer process. is.allow_wasm_code_generation_callback = AllowWasmCodeGenerationCallback; is.flags |= node::IsolateSettingsFlags:: ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK; is.modify_code_generation_from_strings_callback = ModifyCodeGenerationFromStrings; if (browser_env_ == BrowserEnvironment::kBrowser || browser_env_ == BrowserEnvironment::kUtility) { // Node.js requires that microtask checkpoints be explicitly invoked. is.policy = v8::MicrotasksPolicy::kExplicit; } else { // Blink expects the microtasks policy to be kScoped, but Node.js expects it // to be kExplicit. In the renderer, there can be many contexts within the // same isolate, so we don't want to change the existing policy here, which // could be either kExplicit or kScoped depending on whether we're executing // from within a Node.js or a Blink entrypoint. Instead, the policy is // toggled to kExplicit when entering Node.js through UvRunOnce. is.policy = context->GetIsolate()->GetMicrotasksPolicy(); // We do not want to use Node.js' message listener as it interferes with // Blink's. is.flags &= ~node::IsolateSettingsFlags::MESSAGE_LISTENER_WITH_ERROR_LEVEL; // Isolate message listeners are additive (you can add multiple), so instead // we add an extra one here to ensure that the async hook stack is properly // cleared when errors are thrown. context->GetIsolate()->AddMessageListenerWithErrorLevel( ErrorMessageListener, v8::Isolate::kMessageError); // We do not want to use the promise rejection callback that Node.js uses, // because it does not send PromiseRejectionEvents to the global script // context. We need to use the one Blink already provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK; // We do not want to use the stack trace callback that Node.js uses, // because it relies on Node.js being aware of the current Context and // that's not always the case. We need to use the one Blink already // provides. is.flags |= node::IsolateSettingsFlags::SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK; } node::SetIsolateUpForNode(context->GetIsolate(), is); gin_helper::Dictionary process(context->GetIsolate(), env->process_object()); process.SetReadOnly("type", process_type); process.Set("resourcesPath", resources_path); // The path to helper app. base::FilePath helper_exec_path; base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); return env; } node::Environment* NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) auto& electron_args = ElectronCommandLine::argv(); std::vector<std::string> args(electron_args.size()); std::transform(electron_args.cbegin(), electron_args.cend(), args.begin(), [](auto& a) { return base::WideToUTF8(a); }); #else auto args = ElectronCommandLine::argv(); #endif return CreateEnvironment(context, platform, args, {}); } void NodeBindings::LoadEnvironment(node::Environment* env) { node::LoadEnvironment(env, node::StartExecutionCallback{}); gin_helper::EmitEvent(env->isolate(), env->process_object(), "loaded"); } void NodeBindings::PrepareEmbedThread() { // IOCP does not change for the process until the loop is recreated, // we ensure that there is only a single polling thread satisfying // the concurrency limit set from CreateIoCompletionPort call by // uv_loop_init for the lifetime of this process. // More background can be found at: // https://github.com/microsoft/vscode/issues/142786#issuecomment-1061673400 if (initialized_) return; // Add dummy handle for libuv, otherwise libuv would quit when there is // nothing to do. uv_async_init(uv_loop_, dummy_uv_handle_.get(), nullptr); // Start worker that will interrupt main loop when having uv events. uv_sem_init(&embed_sem_, 0); uv_thread_create(&embed_thread_, EmbedThreadRunner, this); } void NodeBindings::StartPolling() { // Avoid calling UvRunOnce if the loop is already active, // otherwise it can lead to situations were the number of active // threads processing on IOCP is greater than the concurrency limit. if (initialized_) return; initialized_ = true; // The MessageLoop should have been created, remember the one in main thread. task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault(); // Run uv loop for once to give the uv__io_poll a chance to add all events. UvRunOnce(); } void NodeBindings::UvRunOnce() { node::Environment* env = uv_env(); // When doing navigation without restarting renderer process, it may happen // that the node environment is destroyed but the message loop is still there. // In this case we should not run uv loop. if (!env) return; v8::HandleScope handle_scope(env->isolate()); // Enter node context while dealing with uv events. v8::Context::Scope context_scope(env->context()); // Node.js expects `kExplicit` microtasks policy and will run microtasks // checkpoints after every call into JavaScript. Since we use a different // policy in the renderer - switch to `kExplicit` and then drop back to the // previous policy value. v8::MicrotaskQueue* microtask_queue = env->context()->GetMicrotaskQueue(); auto old_policy = microtask_queue->microtasks_policy(); DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_BEGIN0("devtools.timeline", "FunctionCall"); // Deal with uv events. int r = uv_run(uv_loop_, UV_RUN_NOWAIT); if (browser_env_ != BrowserEnvironment::kBrowser) TRACE_EVENT_END0("devtools.timeline", "FunctionCall"); microtask_queue->set_microtasks_policy(old_policy); if (r == 0) base::RunLoop().QuitWhenIdle(); // Quit from uv. // Tell the worker thread to continue polling. uv_sem_post(&embed_sem_); } void NodeBindings::WakeupMainThread() { DCHECK(task_runner_); task_runner_->PostTask(FROM_HERE, base::BindOnce(&NodeBindings::UvRunOnce, weak_factory_.GetWeakPtr())); } void NodeBindings::WakeupEmbedThread() { uv_async_send(dummy_uv_handle_.get()); } // static void NodeBindings::EmbedThreadRunner(void* arg) { auto* self = static_cast<NodeBindings*>(arg); while (true) { // Wait for the main loop to deal with events. uv_sem_wait(&self->embed_sem_); if (self->embed_closed_) break; // Wait for something to happen in uv loop. // Note that the PollEvents() is implemented by derived classes, so when // this class is being destructed the PollEvents() would not be available // anymore. Because of it we must make sure we only invoke PollEvents() // when this class is alive. self->PollEvents(); if (self->embed_closed_) break; // Deal with event in main thread. self->WakeupMainThread(); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/common/node_bindings.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #include <string> #include <type_traits> #include <vector> #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" #include "uv.h" // NOLINT(build/include_directory) #include "v8/include/v8.h" namespace base { class SingleThreadTaskRunner; } namespace node { class Environment; class MultiIsolatePlatform; class IsolateData; } // namespace node namespace electron { // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before // memory is released. Moreover, the memory can only be released in // close_cb or after it has returned." This class encapsulates the work // needed to follow those requirements. template <typename T, typename std::enable_if< // these are the C-style 'subclasses' of uv_handle_t std::is_same<T, uv_async_t>::value || std::is_same<T, uv_check_t>::value || std::is_same<T, uv_fs_event_t>::value || std::is_same<T, uv_fs_poll_t>::value || std::is_same<T, uv_idle_t>::value || std::is_same<T, uv_pipe_t>::value || std::is_same<T, uv_poll_t>::value || std::is_same<T, uv_prepare_t>::value || std::is_same<T, uv_process_t>::value || std::is_same<T, uv_signal_t>::value || std::is_same<T, uv_stream_t>::value || std::is_same<T, uv_tcp_t>::value || std::is_same<T, uv_timer_t>::value || std::is_same<T, uv_tty_t>::value || std::is_same<T, uv_udp_t>::value>::type* = nullptr> class UvHandle { public: UvHandle() : t_(new T) {} ~UvHandle() { reset(); } T* get() { return t_; } uv_handle_t* handle() { return reinterpret_cast<uv_handle_t*>(t_); } void reset() { auto* h = handle(); if (h != nullptr) { DCHECK_EQ(0, uv_is_closing(h)); uv_close(h, OnClosed); t_ = nullptr; } } private: static void OnClosed(uv_handle_t* handle) { delete reinterpret_cast<T*>(handle); } RAW_PTR_EXCLUSION T* t_ = {}; }; class NodeBindings { public: enum class BrowserEnvironment { kBrowser, kRenderer, kUtility, kWorker }; static NodeBindings* Create(BrowserEnvironment browser_env); static void RegisterBuiltinBindings(); static bool IsInitialized(); virtual ~NodeBindings(); // Setup V8, libuv. void Initialize(v8::Local<v8::Context> context); void SetNodeCliFlags(); // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args); node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); // Prepare embed thread for message loop integration. void PrepareEmbedThread(); // Notify embed thread to start polling after environment is loaded. void StartPolling(); // Gets/sets the per isolate data. void set_isolate_data(node::IsolateData* isolate_data) { isolate_data_ = isolate_data; } node::IsolateData* isolate_data() const { return isolate_data_; } // Gets/sets the environment to wrap uv loop. void set_uv_env(node::Environment* env) { uv_env_ = env; } node::Environment* uv_env() const { return uv_env_; } uv_loop_t* uv_loop() const { return uv_loop_; } bool in_worker_loop() const { return uv_loop_ == &worker_loop_; } // disable copy NodeBindings(const NodeBindings&) = delete; NodeBindings& operator=(const NodeBindings&) = delete; protected: explicit NodeBindings(BrowserEnvironment browser_env); // Called to poll events in new thread. virtual void PollEvents() = 0; // Run the libuv loop for once. void UvRunOnce(); // Make the main thread run libuv loop. void WakeupMainThread(); // Interrupt the PollEvents. void WakeupEmbedThread(); // Which environment we are running. const BrowserEnvironment browser_env_; // Current thread's MessageLoop. scoped_refptr<base::SingleThreadTaskRunner> task_runner_; // Current thread's libuv loop. raw_ptr<uv_loop_t> uv_loop_; private: // Thread to poll uv events. static void EmbedThreadRunner(void* arg); // Indicates whether polling thread has been created. bool initialized_ = false; // Whether the libuv loop has ended. bool embed_closed_ = false; // Loop used when constructed in WORKER mode uv_loop_t worker_loop_; // Dummy handle to make uv's loop not quit. UvHandle<uv_async_t> dummy_uv_handle_; // Thread for polling events. uv_thread_t embed_thread_; // Semaphore to wait for main loop in the embed thread. uv_sem_t embed_sem_; // Environment that to wrap the uv loop. raw_ptr<node::Environment> uv_env_ = nullptr; // Isolate data used in creating the environment raw_ptr<node::IsolateData> isolate_data_ = nullptr; base::WeakPtrFactory<NodeBindings> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
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 "base/command_line.h" #include "base/containers/contains.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-with-error-code"; 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 (!base::Contains(injected_frames_, render_frame)) 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); return base::Contains(environments_, env) ? env : nullptr; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
shell/renderer/web_worker_observer.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/renderer/web_worker_observer.h" #include <utility> #include "base/no_destructor.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" namespace electron { namespace { static base::NoDestructor<base::ThreadLocalOwnedPointer<WebWorkerObserver>> lazy_tls; } // namespace // static WebWorkerObserver* WebWorkerObserver::GetCurrent() { return lazy_tls->Get(); } // static WebWorkerObserver* WebWorkerObserver::Create() { auto obs = std::make_unique<WebWorkerObserver>(); auto* obs_raw = obs.get(); lazy_tls->Set(std::move(obs)); return obs_raw; } WebWorkerObserver::WebWorkerObserver() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kWorker)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} WebWorkerObserver::~WebWorkerObserver() { // 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` v8::MicrotaskQueue* microtask_queue = node_bindings_->uv_env()->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(node_bindings_->uv_env()); node::FreeIsolateData(node_bindings_->isolate_data()); microtask_queue->set_microtasks_policy(old_policy); } void WebWorkerObserver::WorkerScriptReadyForEvaluation( v8::Local<v8::Context> worker_context) { v8::Context::Scope context_scope(worker_context); auto* isolate = worker_context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, worker_context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); // Start the embed thread. 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(worker_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // 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 WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { node::Environment* env = node::Environment::GetCurrent(context); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); if (lazy_tls->Get()) lazy_tls->Set(nullptr); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
37,404
[Bug]: proxyquire can't load modules after window.open method is called
### 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? Windows ### Operating System Version Windows 11, Version22H2, OS Build 22621.1265 ### What arch are you using? x64 ### Last Known Working Electron version 22.3.1 ### Expected Behavior proxyquire should load modules as it does with electron version 22.3.1. ### Actual Behavior Attempt to use proxyquire in tests with electron of version 23 an higher leads to the following error message: ``` TypeError: Script methods can only be called on script instances. at Script.runInThisContext (node:vm:129:12) at Object.runInThisContext (node:vm:313:38) at wrapSafe (node:internal/modules/cjs/loader:1083:15) at Module._compile (node:internal/modules/cjs/loader:1130:27) at Module._extensions..js (node:internal/modules/cjs/loader:1229:10) at require.extensions.<computed> (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:311:43) at Module.load (node:internal/modules/cjs/loader:1044:32) at Module._load (node:internal/modules/cjs/loader:885:12) at f._load (node:electron/js2c/asar_bundle:2:13330) at o._load (node:electron/js2c/renderer_init:2:3109) at Module.require (node:internal/modules/cjs/loader:1068:19) at Proxyquire._withoutCache (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:222:12) at Proxyquire.load (C:\work\proxyquire-test\node_modules\proxyquire\lib\proxyquire.js:129:15) at Context.<anonymous> (C:\work\proxyquire-test\test.spec.js:7:5) at callFn (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:366:21) at Runnable.run (C:\work\proxyquire-test\node_modules\mocha\lib\runnable.js:354:5) at Runner.runTest (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:678:10) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:801:12 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:593:14) at C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:603:7 at next (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:486:14) at Immediate._onImmediate (C:\work\proxyquire-test\node_modules\mocha\lib\runner.js:571:5) at process.processImmediate (node:internal/timers:471:21) ``` ### Testcase Gist URL https://gist.github.com/kyrylo-hrechykhin/f0afe7c469145c51d4df39fbea97ec95 ### Additional Information #### Workarounds: - avoid calling window.open method completely - separate electron-mocha runs to the one where window.open method is called and the one where proxyquire is used. If it happens in two different files, it is easy to do. #### Details: Issue is probably caused by node version upgrade in electron 23. But as it worked in electron 22, I consider it as a regression. I also could not reproduce this issue in non-electron environment. #### Run testcase gist locally: Run the following commands in the folder where all the files specified in the attached gist. ``` yarn yarn start ``` Please upgrade/downgrade electron versions to see actual/expected results.
https://github.com/electron/electron/issues/37404
https://github.com/electron/electron/pull/38754
4ab0a5ade47534db85d333e17f40530cc9726475
8874306dc021f2beb4c2b7cd49b8f3bec614e373
2023-02-24T16:47:53Z
c++
2023-07-18T08:41:50Z
spec/chromium-spec.ts
import { expect } from 'chai'; import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main'; import { closeAllWindows } from './lib/window-helpers'; import * as https from 'node:https'; import * as http from 'node:http'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as url from 'node:url'; import * as ChildProcess from 'node:child_process'; import { EventEmitter, once } from 'node:events'; import { promisify } from 'node:util'; import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; const features = process._linkedBinding('electron_common_features'); const fixturesPath = path.resolve(__dirname, 'fixtures'); const certPath = path.join(fixturesPath, 'certificates'); describe('reporting api', () => { it('sends a report for an intervention', async () => { const reporting = new EventEmitter(); // The Reporting API only works on https with valid certs. To dodge having // to set up a trusted certificate, hack the validator. session.defaultSession.setCertificateVerifyProc((req, cb) => { cb(0); }); const options = { key: fs.readFileSync(path.join(certPath, 'server.key')), cert: fs.readFileSync(path.join(certPath, 'server.pem')), ca: [ fs.readFileSync(path.join(certPath, 'rootCA.pem')), fs.readFileSync(path.join(certPath, 'intermediateCA.pem')) ], requestCert: true, rejectUnauthorized: false }; const server = https.createServer(options, (req, res) => { if (req.url?.endsWith('report')) { let data = ''; req.on('data', (d) => { data += d.toString('utf-8'); }); req.on('end', () => { reporting.emit('report', JSON.parse(data)); }); } const { port } = server.address() as any; res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`); res.setHeader('Content-Type', 'text/html'); res.end('<script>window.navigator.vibrate(1)</script>'); }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); const { type, url, body } = reports[0]; expect(type).to.equal('intervention'); expect(url).to.equal(url); expect(body.id).to.equal('NavigatorVibrate'); expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/); } finally { bw.destroy(); server.close(); } }); }); describe('window.postMessage', () => { afterEach(async () => { await closeAllWindows(); }); it('sets the source and origin correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`); const [, message] = await once(ipcMain, 'complete'); expect(message.data).to.equal('testing'); expect(message.origin).to.equal('file://'); expect(message.sourceEqualsOpener).to.equal(true); expect(message.eventOrigin).to.equal('file://'); }); }); describe('focus handling', () => { let webviewContents: WebContents; let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>; await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html')); const [, wvContents] = await webviewReady; webviewContents = wvContents; await once(webviewContents, 'did-finish-load'); w.focus(); }); afterEach(() => { webviewContents = null as unknown as WebContents; w.destroy(); w = null as unknown as BrowserWindow; }); const expectFocusChange = async () => { const [, focusedElementId] = await once(ipcMain, 'focus-changed'); return focusedElementId; }; describe('a TAB press', () => { const tabPressEvent: any = { type: 'keyDown', keyCode: 'Tab' }; it('moves focus to the next focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(tabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`); }); }); describe('a SHIFT + TAB press', () => { const shiftTabPressEvent: any = { type: 'keyDown', modifiers: ['Shift'], keyCode: 'Tab' }; it('moves focus to the previous focusable item', async () => { let focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); let focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); webviewContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`); focusChange = expectFocusChange(); w.webContents.sendInputEvent(shiftTabPressEvent); focusedElementId = await focusChange; expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`); }); }); }); describe('web security', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); it('engages CORB when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html,<script> const s = document.createElement('script') s.src = "${serverUrl}" // The script will load successfully but its body will be emptied out // by CORB, so we don't expect a syntax error. s.onload = () => { require('electron').ipcRenderer.send('success') } document.documentElement.appendChild(s) </script>`); await p; }); it('bypasses CORB when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'success'); await w.loadURL(`data:text/html, <script> window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) } </script> <script src="${serverUrl}"></script>`); await p; }); it('engages CORS when web security is not disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('failed'); }); it('bypasses CORS when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } }); const p = once(ipcMain, 'response'); await w.loadURL(`data:text/html,<script> (async function() { try { await fetch('${serverUrl}'); require('electron').ipcRenderer.send('response', 'passed'); } catch { require('electron').ipcRenderer.send('response', 'failed'); } })(); </script>`); const [, response] = await p; expect(response).to.equal('passed'); }); describe('accessing file://', () => { async function loadFile (w: BrowserWindow) { const thisFile = url.format({ pathname: __filename.replace(/\\/g, '/'), protocol: 'file', slashes: true }); await w.loadURL(`data:text/html,<script> function loadFile() { return new Promise((resolve) => { fetch('${thisFile}').then( () => resolve('loaded'), () => resolve('failed') ) }); } </script>`); return await w.webContents.executeJavaScript('loadFile()'); } it('is forbidden when web security is enabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } }); const result = await loadFile(w); expect(result).to.equal('failed'); }); it('is allowed when web security is disabled', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } }); const result = await loadFile(w); expect(result).to.equal('loaded'); }); }); describe('wasm-eval csp', () => { async function loadWasm (csp: string) { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, enableBlinkFeatures: 'WebAssemblyCSP' } }); await w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}"> </head> <script> function loadWasm() { const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) return new Promise((resolve) => { WebAssembly.instantiate(wasmBin).then(() => { resolve('loaded') }).catch((error) => { resolve(error.message) }) }); } </script>`); return await w.webContents.executeJavaScript('loadWasm()'); } it('wasm codegen is disallowed by default', async () => { const r = await loadWasm(''); expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"'); }); it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => { const r = await loadWasm("'wasm-unsafe-eval'"); expect(r).to.equal('loaded'); }); }); describe('csp', () => { for (const sandbox of [true, false]) { describe(`when sandbox: ${sandbox}`, () => { for (const contextIsolation of [true, false]) { describe(`when contextIsolation: ${contextIsolation}`, () => { it('prevents eval from running in an inline script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html,<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'"> </head> <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.match(/Refused to evaluate a string/); }); it('does not prevent eval from running in an inline script when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL(`data:text/html, <script> try { // We use console.log here because it is easier than making a // preload script, and the behavior under test changes when // contextIsolation: false console.log(eval('true')) } catch (e) { console.log(e.message) } </script>`); const [,, message] = await once(w.webContents, 'console-message'); expect(message).to.equal('true'); }); it('prevents eval from running in executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>'); await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected(); }); it('does not prevent eval from running in executeJavaScript when there is no csp', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, contextIsolation } }); w.loadURL('data:text/html,'); expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true(); }); }); } }); } }); it('does not crash when multiple WebContent are created with web security disabled', () => { const options = { show: false, webPreferences: { webSecurity: false } }; const w1 = new BrowserWindow(options); w1.loadURL(serverUrl); const w2 = new BrowserWindow(options); w2.loadURL(serverUrl); }); }); describe('command line switches', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); describe('--lang switch', () => { const currentLocale = app.getLocale(); const currentSystemLocale = app.getSystemLocale(); const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages()); const testLocale = async (locale: string, result: string, printEnv: boolean = false) => { const appPath = path.join(fixturesPath, 'api', 'locale-check'); const args = [appPath, `--set-lang=${locale}`]; if (printEnv) { args.push('--print-env'); } appProcess = ChildProcess.spawn(process.execPath, args); let output = ''; appProcess.stdout.on('data', (data) => { output += data; }); let stderr = ''; appProcess.stderr.on('data', (data) => { stderr += data; }); const [code, signal] = await once(appProcess, 'exit'); if (code !== 0) { throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`); } output = output.replace(/(\r\n|\n|\r)/gm, ''); expect(output).to.equal(result); }; it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`)); it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`)); const lcAll = String(process.env.LC_ALL); ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => { // The LC_ALL env should not be set to DOM locale string. expect(lcAll).to.not.equal(app.getLocale()); }); ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true)); ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true)); }); describe('--remote-debugging-pipe switch', () => { it('should expose CDP via pipe', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(message.result.product).to.contain('Chrome'); expect(message.result.userAgent).to.contain('Electron'); }); it('should override --remote-debugging-port switch', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], { stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; let stderr = ''; appProcess.stderr.on('data', (data: string) => { stderr += data; }); const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; }); pipe.send({ id: 1, method: 'Browser.getVersion', params: {} }); const message = (await versionPromise) as any; expect(message.id).to.equal(1); expect(stderr).to.not.include('DevTools listening on'); }); it('should shut down Electron upon Browser.close CDP command', async () => { const electronPath = process.execPath; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'] }) as ChildProcess.ChildProcessWithoutNullStreams; const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream]; const pipe = new PipeTransport(stdio[3], stdio[4]); pipe.send({ id: 1, method: 'Browser.close', params: {} }); await once(appProcess, 'exit'); }); }); describe('--remote-debugging-port switch', () => { it('should display the discovery page', (done) => { const electronPath = process.execPath; let output = ''; appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']); appProcess.stdout.on('data', (data) => { console.log(data); }); appProcess.stderr.on('data', (data) => { console.log(data); output += data; const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output); if (m) { appProcess!.stderr.removeAllListeners('data'); const port = m[1]; http.get(`http://127.0.0.1:${port}`, (res) => { try { expect(res.statusCode).to.eql(200); expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0); done(); } catch (e) { done(e); } finally { res.destroy(); } }); } }); }); }); }); describe('chromium features', () => { afterEach(closeAllWindows); describe('accessing key names also used as Node.js module names', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html')); }); }); describe('first party sets', () => { const fps = [ 'https://fps-member1.glitch.me', 'https://fps-member2.glitch.me', 'https://fps-member3.glitch.me' ]; it('loads first party sets', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base'); const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); it('loads sets from the command line', async () => { const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line'); const args = [appPath, `--use-first-party-set=${fps}`]; const fpsProcess = ChildProcess.spawn(process.execPath, args); let output = ''; fpsProcess.stdout.on('data', data => { output += data; }); await once(fpsProcess, 'exit'); expect(output).to.include(fps.join(',')); }); }); describe('loading jquery', () => { it('does not crash', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('did-finish-load', () => { done(); }); w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html')); }); }); describe('navigator.languages', () => { it('should return the system locale only', async () => { const appLocale = app.getLocale(); const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const languages = await w.webContents.executeJavaScript('navigator.languages'); expect(languages.length).to.be.greaterThan(0); expect(languages).to.contain(appLocale); }); }); describe('navigator.serviceWorker', () => { it('should register for file scheme', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for intercepted file scheme', (done) => { const customSession = session.fromPartition('intercept-file'); customSession.protocol.interceptBufferProtocol('file', (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); const content = fs.readFileSync(path.normalize(file)); const ext = path.extname(file); let type = 'text/html'; if (ext === '.js') type = 'application/javascript'; callback({ data: content, mimeType: type } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol('file'); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html')); }); it('should register for custom scheme', (done) => { const customSession = session.fromPartition('custom-scheme'); customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => { let file = url.parse(request.url).pathname!; if (file[0] === '/' && process.platform === 'win32') file = file.slice(1); callback({ path: path.normalize(file) } as any); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: customSession, contextIsolation: false } }); w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(`unexpected error : ${message}`); } else if (channel === 'response') { expect(message).to.equal('Hello from serviceWorker!'); customSession.clearStorageData({ storages: ['serviceworkers'] }).then(() => { customSession.protocol.uninterceptProtocol(serviceWorkerScheme); done(); }); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html')); }); it('should not allow nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, partition: 'sw-file-scheme-worker-spec', contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`); const data = await w.webContents.executeJavaScript(` navigator.serviceWorker.register('worker-no-node.js', { scope: './' }).then(() => navigator.serviceWorker.ready) new Promise((resolve) => { navigator.serviceWorker.onmessage = event => resolve(event.data); }); `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); describe('navigator.geolocation', () => { ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'geolocation-spec', contextIsolation: false } }); const message = once(w.webContents, 'ipc-message'); w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'geolocation') { callback(false); } else { callback(true); } }); w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html')); const [, channel] = await message; expect(channel).to.equal('success', 'unexpected response from geolocation api'); }); ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => { const w = new BrowserWindow({ show: false, webPreferences: { partition: 'geolocation-spec' } }); w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => { callback(true); }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition( x => resolve({coords: x.coords, timestamp: x.timestamp}), err => reject(new Error(err.message))))`); expect(position).to.have.property('coords'); expect(position).to.have.property('timestamp'); }); }); describe('web workers', () => { let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths'); appProcess = ChildProcess.spawn(process.execPath, [appPath]); const [code] = await once(appProcess, 'exit'); expect(code).to.equal(0); }); it('Worker can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; }); worker.postMessage(message); eventPromise.then(t => t.data) `); expect(data).to.equal('ping'); }); it('Worker has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new Worker('../workers/worker_node.js'); new Promise((resolve) => { worker.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('Worker has node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); w.loadURL(`file://${fixturesPath}/pages/worker.html`); const [, data] = await once(ipcMain, 'worker-result'); expect(data).to.equal('object function object function'); }); describe('SharedWorker', () => { it('can work', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker.js'); const message = 'ping'; const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }); worker.port.postMessage(message); eventPromise `); expect(data).to.equal('ping'); }); it('has no node integration by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); it('does not have node integration with nodeIntegrationInWorker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const data = await w.webContents.executeJavaScript(` const worker = new SharedWorker('../workers/shared_worker_node.js'); new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); }) `); expect(data).to.equal('undefined undefined undefined undefined'); }); }); }); describe('form submit', () => { let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { let body = ''; req.on('data', (chunk) => { body += chunk; }); res.setHeader('Content-Type', 'application/json'); req.on('end', () => { res.end(`body:${body}`); }); }); serverUrl = (await listen(server)).url; }); after(async () => { server.close(); await closeAllWindows(); }); [true, false].forEach((isSandboxEnabled) => describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const loadPromise = once(w.webContents, 'did-finish-load'); w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.submit(); `); await loadPromise; const res = await w.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); it('posts data to a new window with target=_blank', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: isSandboxEnabled } }); await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html')); const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.webContents.executeJavaScript(` const form = document.querySelector('form') form.action = '${serverUrl}'; form.target = '_blank'; form.submit(); `); const [, newWin] = await windowCreatedPromise; const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); }) ); }); describe('window.open', () => { for (const show of [true, false]) { it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => { const w = new BrowserWindow({ show }); // toggle visibility if (show) { w.hide(); } else { w.show(); } defer(() => { w.close(); }); const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>; w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html')); const [, newWindow] = await promise; expect(newWindow.isVisible()).to.equal(true); }); } // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isProcessGlobalUndefined).to.be.true(); }); it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => { // NB. webSecurity is disabled because native window.open() is not // allowed to load devtools:// URLs. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); it('can disable node integration when it is enabled on the parent window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` { b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; const typeofProcessGlobal = await contents.executeJavaScript('typeof process'); expect(typeofProcessGlobal).to.equal('undefined'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = require('node:url').format({ pathname: `${fixturesPath}/pages/window-no-javascript.html`, protocol: 'file', slashes: true }); w.webContents.executeJavaScript(` { b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null } `); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-finish-load'); // Click link on page contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 }); contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 }); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; const preferences = window.webContents.getLastWebPreferences(); expect(preferences!.javascript).to.be.false(); }); it('defines a window.location getter', async () => { let targetURL: string; if (process.platform === 'win32') { targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`; } else { targetURL = `file://${fixturesPath}/pages/base-page.html`; } const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`); const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(window.webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL); }); it('defines a window.location setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('defines a window.location.href setter', async () => { const w = new BrowserWindow({ show: false }); w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); // When it loads, redirect w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`); await once(webContents, 'did-finish-load'); }); it('open a blank page when no URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('open a blank page when an empty URL is specified', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\'); null }'); const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow]; await once(webContents, 'did-finish-load'); expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank'); }); it('does not throw an exception when the frameName is a built-in object property', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }'); const frameName = await new Promise((resolve) => { w.webContents.setWindowOpenHandler(details => { setImmediate(() => resolve(details.frameName)); return { action: 'allow' }; }); }); expect(frameName).to.equal('__proto__'); }); // FIXME(nornagon): I'm not sure this ... ever was correct? xit('inherit options of parent window', async () => { const w = new BrowserWindow({ show: false, width: 123, height: 456 }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const url = `file://${fixturesPath}/pages/window-open-size.html`; const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(url)}, '', 'show=false') const e = await message b.close(); const width = outerWidth; const height = outerHeight; return { width, height, eventData: e.data } })()`); expect(eventData).to.equal(`size: ${width} ${height}`); expect(eventData).to.equal('size: 123 456'); }); it('does not override child options', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`; const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData).to.equal('size: 350 450'); }); it('loads preload script after setting opener to null', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(fixturesPath, 'module', 'preload.js') } } })); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.child = window.open(); child.opener = null'); const [, { webContents }] = await once(app, 'browser-window-created'); const [,, message] = await once(webContents, 'console-message'); expect(message).to.equal('{"require":"function","module":"undefined","process":"object","Buffer":"function"}'); }); it('disables the <webview> tag when it is disabled on the parent window', async () => { const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html')); windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`); const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const { eventData } = await w.webContents.executeJavaScript(`(async () => { const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true})); const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no') const e = await message b.close(); return { eventData: e.data } })()`); expect(eventData.isWebViewGlobalUndefined).to.be.true(); }); it('throws an exception when the arguments cannot be converted to strings', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', { toString: null })') ).to.eventually.be.rejected(); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })') ).to.eventually.be.rejected(); }); it('does not throw an exception when the features include webPreferences', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await expect( w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null') ).to.eventually.be.fulfilled(); }); }); describe('window.opener', () => { it('is null for main window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html')); const [, channel, opener] = await once(w.webContents, 'ipc-message'); expect(channel).to.equal('opener'); expect(opener).to.equal(null); }); it('is not null for window opened by window.open', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener.html`; const eventData = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data); `); expect(eventData).to.equal('object'); }); }); describe('window.opener.postMessage', () => { it('sets source and origin correctly', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`; const { sourceIsChild, origin } = await w.webContents.executeJavaScript(` const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({ sourceIsChild: e.source === b, origin: e.origin })); `); expect(sourceIsChild).to.be.true(); expect(origin).to.equal('file://'); }); it('supports windows opened from a <webview>', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('about:blank'); const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html')); childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`); const message = await w.webContents.executeJavaScript(` const webview = new WebView(); webview.allowpopups = true; webview.setAttribute('webpreferences', 'contextIsolation=no'); webview.src = ${JSON.stringify(childWindowUrl)} const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true})); document.body.appendChild(webview); consoleMessage.then(e => e.message) `); expect(message).to.equal('message'); }); describe('targetOrigin argument', () => { let serverURL: string; let server: any; beforeEach(async () => { server = http.createServer((req, res) => { res.writeHead(200); const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html'); res.end(fs.readFileSync(filePath, 'utf8')); }); serverURL = (await listen(server)).url; }); afterEach(() => { server.close(); }); it('delivers messages that match the origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html')); const data = await w.webContents.executeJavaScript(` window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes'); new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data) `); expect(data).to.equal('deliver'); }); }); }); describe('navigator.mediaDevices', () => { afterEach(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setPermissionRequestHandler(null); }); it('can return labels of enumerated devices', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.true(); }); it('does not return labels of enumerated devices when permission denied', async () => { session.defaultSession.setPermissionCheckHandler(() => false); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))'); expect(labels.some((l: any) => l)).to.be.false(); }); it('returns the same device ids across reloads', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.deep.equal(secondDeviceIds); }); it('can return new device id when cookie storage is cleared', async () => { const ses = session.fromPartition('persist:media-device-id'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, session: ses, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html')); const [, firstDeviceIds] = await once(ipcMain, 'deviceIds'); await ses.clearStorageData({ storages: ['cookies'] }); w.webContents.reload(); const [, secondDeviceIds] = await once(ipcMain, 'deviceIds'); expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds); }); it('provides a securityOrigin to the request handler', async () => { session.defaultSession.setPermissionRequestHandler( (wc, permission, callback, details) => { if (details.securityOrigin !== undefined) { callback(true); } else { callback(false); } } ); const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({ video: { mandatory: { chromeMediaSource: "desktop", minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }).then((stream) => stream.getVideoTracks())`); expect(labels.some((l: any) => l)).to.be.true(); }); it('fails with "not supported" for getDisplayMedia', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true); expect(ok).to.be.false(); expect(err).to.equal('Not supported'); }); }); describe('window.opener access', () => { const scheme = 'app'; const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`; const httpUrl1 = `${scheme}://origin1`; const httpUrl2 = `${scheme}://origin2`; const fileBlank = `file://${fixturesPath}/pages/blank.html`; const httpBlank = `${scheme}://origin1/blank`; const table = [ { parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false }, { parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false }, // {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open() // {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open() // NB. this is different from Chrome's behavior, which isolates file: urls from each other { parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true }, { parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true }, { parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true }, { parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false }, { parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false } ]; const s = (url: string) => url.startsWith('file') ? 'file://...' : url; before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { if (request.url.includes('blank')) { callback(`${fixturesPath}/pages/blank.html`); } else { callback(`${fixturesPath}/pages/window-opener-location.html`); } }); }); after(() => { protocol.unregisterProtocol(scheme); }); afterEach(closeAllWindows); describe('when opened from main window', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { for (const sandboxPopup of [false, true]) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { sandbox: sandboxPopup } } })); await w.loadURL(parent); const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => { window.addEventListener('message', function f(e) { resolve(e.data) }) window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}") })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } } }); describe('when opened from <webview>', () => { for (const { parent, child, nodeIntegration, openerAccessible } of table) { const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`; it(description, async () => { // This test involves three contexts: // 1. The root BrowserWindow in which the test is run, // 2. A <webview> belonging to the root window, // 3. A window opened by calling window.open() from within the <webview>. // We are testing whether context (3) can access context (2) under various conditions. // This is context (1), the base window for the test. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } }); await w.loadURL('about:blank'); const parentCode = `new Promise((resolve) => { // This is context (3), a child window of the WebView. const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes") window.addEventListener("message", e => { resolve(e.data) }) })`; const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => { // This is context (2), a WebView which will call window.open() const webview = new WebView() webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}') webview.setAttribute('webpreferences', 'contextIsolation=no') webview.setAttribute('allowpopups', 'on') webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))} webview.addEventListener('dom-ready', async () => { webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject) }) document.body.appendChild(webview) })`); if (openerAccessible) { expect(childOpenerLocation).to.be.a('string'); } else { expect(childOpenerLocation).to.be.null(); } }); } }); }); describe('storage', () => { describe('custom non standard schemes', () => { const protocolName = 'storage'; let contents: WebContents; before(() => { protocol.registerFileProtocol(protocolName, (request, callback) => { const parsedUrl = url.parse(request.url); let filename; switch (parsedUrl.pathname) { case '/localStorage' : filename = 'local_storage.html'; break; case '/sessionStorage' : filename = 'session_storage.html'; break; case '/WebSQL' : filename = 'web_sql.html'; break; case '/indexedDB' : filename = 'indexed_db.html'; break; case '/cookie' : filename = 'cookie.html'; break; default : filename = ''; } callback({ path: `${fixturesPath}/pages/storage/${filename}` }); }); }); after(() => { protocol.unregisterProtocol(protocolName); }); beforeEach(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); }); afterEach(() => { contents.destroy(); contents = null as any; }); it('cannot access localStorage', async () => { const response = once(ipcMain, 'local-storage-response'); contents.loadURL(protocolName + '://host/localStorage'); const [, error] = await response; expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access sessionStorage', async () => { const response = once(ipcMain, 'session-storage-response'); contents.loadURL(`${protocolName}://host/sessionStorage`); const [, error] = await response; expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.'); }); it('cannot access WebSQL database', async () => { const response = once(ipcMain, 'web-sql-response'); contents.loadURL(`${protocolName}://host/WebSQL`); const [, error] = await response; expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.'); }); it('cannot access indexedDB', async () => { const response = once(ipcMain, 'indexed-db-response'); contents.loadURL(`${protocolName}://host/indexedDB`); const [, error] = await response; expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.'); }); it('cannot access cookie', async () => { const response = once(ipcMain, 'cookie-response'); contents.loadURL(`${protocolName}://host/cookie`); const [, error] = await response; expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.'); }); }); describe('can be accessed', () => { let server: http.Server; let serverUrl: string; let serverCrossSiteUrl: string; before(async () => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${serverCrossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else { res.end(); } }; setTimeout().then(respond); }); serverUrl = (await listen(server)).url; serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); }); after(() => { server.close(); server = null as any; }); afterEach(closeAllWindows); const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => { it(testTitle, async () => { const w = new BrowserWindow({ show: false, ...extraPreferences }); let redirected = false; w.webContents.on('render-process-gone', () => { expect.fail('renderer crashed / was killed'); }); w.webContents.on('did-redirect-navigation', (event, url) => { expect(url).to.equal(`${serverCrossSiteUrl}/redirected`); redirected = true; }); await w.loadURL(`${serverUrl}/redirect-cross-site`); expect(redirected).to.be.true('didnt redirect'); }); }; testLocalStorageAfterXSiteRedirect('after a cross-site redirect'); testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true }); }); describe('enableWebSQL webpreference', () => { const origin = `${standardScheme}://fake-host`; const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html'); const sqlPartition = 'web-sql-preference-test'; const sqlSession = session.fromPartition(sqlPartition); const securityError = 'An attempt was made to break through the security policy of the user agent.'; let contents: WebContents, w: BrowserWindow; before(() => { sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => { callback({ path: filePath }); }); }); after(() => { sqlSession.protocol.unregisterProtocol(standardScheme); }); afterEach(async () => { if (contents) { contents.destroy(); contents = null as any; } await closeAllWindows(); (w as any) = null; }); it('default value allows websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); }); it('when set to false can disallow websql', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); }); it('when set to false does not disable indexedDB', async () => { contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, contextIsolation: false }); contents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.equal(securityError); const dbName = 'random'; const result = await contents.executeJavaScript(` new Promise((resolve, reject) => { try { let req = window.indexedDB.open('${dbName}'); req.onsuccess = (event) => { let db = req.result; resolve(db.name); } req.onerror = (event) => { resolve(event.target.code); } } catch (e) { resolve(e.message); } }); `); expect(result).to.equal(dbName); }); it('child webContents can override when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents cannot override when the embedder has disallowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableWebSQL: false, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL('data:text/html,<html></html>'); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.equal(securityError); }); it('child webContents can use websql when the embedder has allowed websql', async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, session: sqlSession, contextIsolation: false } }); w.webContents.loadURL(origin); const [, error] = await once(ipcMain, 'web-sql-response'); expect(error).to.be.null(); const webviewResult = once(ipcMain, 'web-sql-response'); await w.webContents.executeJavaScript(` new Promise((resolve, reject) => { const webview = new WebView(); webview.setAttribute('src', '${origin}'); webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no'); webview.setAttribute('partition', '${sqlPartition}'); webview.setAttribute('nodeIntegration', 'on'); document.body.appendChild(webview); webview.addEventListener('dom-ready', () => resolve()); }); `); const [, childError] = await webviewResult; expect(childError).to.be.null(); }); }); describe('DOM storage quota increase', () => { ['localStorage', 'sessionStorage'].forEach((storageName) => { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // Although JavaScript strings use UTF-16, the underlying // storage provider may encode strings differently, muddling the // translation between character and byte counts. However, // a string of 40 * 2^20 characters will require at least 40MiB // and presumably no more than 80MiB, a size guaranteed to // to exceed the original 10MiB quota yet stay within the // new 100MiB quota. // Note that both the key name and value affect the total size. const testKeyName = '_electronDOMStorageQuotaIncreasedTest'; const length = 40 * Math.pow(2, 20) - testKeyName.length; await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); // Wait at least one turn of the event loop to help avoid false positives // Although not entirely necessary, the previous version of this test case // failed to detect a real problem (perhaps related to DOM storage data caching) // wherein calling `getItem` immediately after `setItem` would appear to work // but then later (e.g. next tick) it would not. await setTimeout(1); try { const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`); expect(storedLength).to.equal(length); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } }); it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); await expect((async () => { const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest'; const length = 128 * Math.pow(2, 20) - testKeyName.length; try { await w.webContents.executeJavaScript(` ${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length})); `); } finally { await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`); } })()).to.eventually.be.rejected(); }); }); }); describe('persistent storage', () => { it('can be requested', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => { navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve); })`); expect(grantedBytes).to.equal(1048576); }); }); }); ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => { const pdfSource = url.format({ pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'), protocol: 'file', slashes: true }); it('successfully loads a PDF file', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); await once(w.webContents, 'did-finish-load'); }); it('opens when loading a pdf resource as top level navigation', async () => { const w = new BrowserWindow({ show: false }); w.loadURL(pdfSource); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); it('opens when loading a pdf resource in a iframe', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html')); const [, contents] = await once(app, 'web-contents-created') as [any, WebContents]; await once(contents, 'did-navigate'); expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html'); }); }); describe('window.history', () => { describe('window.history.pushState', () => { it('should push state after calling history.pushState() from the same url', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); // History should have current page by now. expect((w.webContents as any).length()).to.equal(1); const waitCommit = once(w.webContents, 'navigation-entry-committed'); w.webContents.executeJavaScript('window.history.pushState({}, "")'); await waitCommit; // Initial page + pushed state. expect((w.webContents as any).length()).to.equal(2); }); }); describe('window.history.back', () => { it('should not allow sandboxed iframe to modify main frame state', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-frame-navigate'), once(w.webContents, 'did-navigate') ]); w.webContents.executeJavaScript('window.history.pushState(1, "")'); await Promise.all([ once(w.webContents, 'navigation-entry-committed'), once(w.webContents, 'did-navigate-in-page') ]); (w.webContents as any).once('navigation-entry-committed', () => { expect.fail('Unexpected navigation-entry-committed'); }); w.webContents.once('did-navigate-in-page', () => { expect.fail('Unexpected did-navigate-in-page'); }); await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()'); expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1); expect((w.webContents as any).getActiveIndex()).to.equal(1); }); }); }); describe('chrome://media-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://media-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('chrome://webrtc-internals', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('chrome://webrtc-internals'); const pageExists = await w.webContents.executeJavaScript( "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" ); expect(pageExists).to.be.true(); }); }); describe('document.hasFocus', () => { it('has correct value when multiple windows are opened', async () => { const w1 = new BrowserWindow({ show: true }); const w2 = new BrowserWindow({ show: true }); const w3 = new BrowserWindow({ show: false }); await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id); let focus = false; focus = await w1.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); focus = await w2.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.true(); focus = await w3.webContents.executeJavaScript( 'document.hasFocus()' ); expect(focus).to.be.false(); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation describe('navigator.connection', () => { it('returns the correct value', async () => { const w = new BrowserWindow({ show: false }); w.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt'); expect(rtt).to.be.a('number'); const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink'); expect(downlink).to.be.a('number'); const effectiveTypes = ['slow-2g', '2g', '3g', '4g']; const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType'); expect(effectiveTypes).to.include(effectiveType); }); }); describe('navigator.userAgentData', () => { // These tests are done on an http server because navigator.userAgentData // requires a secure context. let server: http.Server; let serverUrl: string; before(async () => { server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end(''); }); serverUrl = (await listen(server)).url; }); after(() => { server.close(); }); describe('is not empty', () => { it('by default', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a session-wide UA override', async () => { const ses = session.fromPartition(`${Math.random()}`); ses.setUserAgent('foobar'); const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setUserAgent('foo'); await w.loadURL(serverUrl); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); it('when there is a WebContents-specific UA override at load time', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl, { userAgent: 'foo' }); const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform'); expect(platform).not.to.be.empty(); }); }); describe('brand list', () => { it('contains chromium', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(serverUrl); const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands'); expect(brands.map((b: any) => b.brand)).to.include('Chromium'); }); }); }); describe('Badging API', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript('navigator.setAppBadge(42)'); await w.webContents.executeJavaScript('navigator.setAppBadge()'); await w.webContents.executeJavaScript('navigator.clearAppBadge()'); }); }); describe('navigator.webkitGetUserMedia', () => { it('calls its callbacks', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); await w.webContents.executeJavaScript(`new Promise((resolve) => { navigator.webkitGetUserMedia({ audio: true, video: false }, () => resolve(), () => resolve()); })`); }); }); describe('navigator.language', () => { it('should not be empty', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal(''); }); }); describe('heap snapshot', () => { it('does not crash', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()'); }); }); // This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761 ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => { it('can be gotten as context in canvas', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const canWebglContextBeCreated = await w.webContents.executeJavaScript(` document.createElement('canvas').getContext('webgl') != null; `); expect(canWebglContextBeCreated).to.be.true(); }); }); describe('iframe', () => { it('does not have node integration', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(`file://${fixturesPath}/pages/blank.html`); const result = await w.webContents.executeJavaScript(` const iframe = document.createElement('iframe') iframe.src = './set-global.html'; document.body.appendChild(iframe); new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test)) `); expect(result).to.equal('undefined undefined undefined'); }); }); describe('websockets', () => { it('has user agent', async () => { const server = http.createServer(); const { port } = await listen(server); const wss = new ws.Server({ server: server }); const finished = new Promise<string | undefined>((resolve, reject) => { wss.on('error', reject); wss.on('connection', (ws, upgradeReq) => { resolve(upgradeReq.headers['user-agent']); }); }); const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript(` new WebSocket('ws://127.0.0.1:${port}'); `); expect(await finished).to.include('Electron'); }); }); describe('fetch', () => { it('does not crash', async () => { const server = http.createServer((req, res) => { res.end('test'); }); defer(() => server.close()); const { port } = await listen(server); const w = new BrowserWindow({ show: false }); w.loadURL(`file://${fixturesPath}/pages/blank.html`); const x = await w.webContents.executeJavaScript(` fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader()) .then((reader) => { return reader.read().then((r) => { reader.cancel(); return r.value; }); }) `); expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116])); }); }); describe('Promise', () => { before(() => { ipcMain.handle('ping', (e, arg) => arg); }); after(() => { ipcMain.removeHandler('ping'); }); itremote('resolves correctly in Node.js calls', async () => { await new Promise<void>((resolve, reject) => { class XElement extends HTMLElement {} customElements.define('x-element', XElement); setImmediate(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('x-element'); called = true; }); }); }); itremote('resolves correctly in Electron calls', async () => { await new Promise<void>((resolve, reject) => { class YElement extends HTMLElement {} customElements.define('y-element', YElement); require('electron').ipcRenderer.invoke('ping').then(() => { let called = false; Promise.resolve().then(() => { if (called) resolve(); else reject(new Error('wrong sequence')); }); document.createElement('y-element'); called = true; }); }); }); }); describe('synchronous prompts', () => { describe('window.alert(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { window.alert({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); describe('window.confirm(message, title)', () => { itremote('throws an exception when the arguments cannot be converted to strings', () => { expect(() => { (window.confirm as any)({ toString: null }, 'title'); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('window.history', () => { describe('window.history.go(offset)', () => { itremote('throws an exception when the argument cannot be converted to a string', () => { expect(() => { (window.history.go as any)({ toString: null }); }).to.throw('Cannot convert object to primitive value'); }); }); }); describe('console functions', () => { itremote('should exist', () => { expect(console.log, 'log').to.be.a('function'); expect(console.error, 'error').to.be.a('function'); expect(console.warn, 'warn').to.be.a('function'); expect(console.info, 'info').to.be.a('function'); expect(console.debug, 'debug').to.be.a('function'); expect(console.trace, 'trace').to.be.a('function'); expect(console.time, 'time').to.be.a('function'); expect(console.timeEnd, 'timeEnd').to.be.a('function'); }); }); // FIXME(nornagon): this is broken on CI, it triggers: // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side // (null text in SpeechSynthesisUtterance struct). describe('SpeechSynthesis', () => { itremote('should emit lifecycle events', async () => { const sentence = `long sentence which will take at least a few seconds to utter so that it's possible to pause and resume before the end`; const utter = new SpeechSynthesisUtterance(sentence); // Create a dummy utterance so that speech synthesis state // is initialized for later calls. speechSynthesis.speak(new SpeechSynthesisUtterance()); speechSynthesis.cancel(); speechSynthesis.speak(utter); // paused state after speak() expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onstart = resolve; }); // paused state after start event expect(speechSynthesis.paused).to.be.false(); speechSynthesis.pause(); // paused state changes async, right before the pause event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onpause = resolve; }); expect(speechSynthesis.paused).to.be.true(); speechSynthesis.resume(); await new Promise((resolve) => { utter.onresume = resolve; }); // paused state after resume event expect(speechSynthesis.paused).to.be.false(); await new Promise((resolve) => { utter.onend = resolve; }); }); }); }); describe('font fallback', () => { async function getRenderedFonts (html: string) { const w = new BrowserWindow({ show: false }); try { await w.loadURL(`data:text/html,${html}`); w.webContents.debugger.attach(); const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams); const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0]; await sendCommand('CSS.enable'); const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId }); return fonts; } finally { w.close(); } } it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => { const html = '<body style="font-family: sans-serif">test</body>'; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.equal('Arial'); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Helvetica'); } else if (process.platform === 'linux') { expect(fonts[0].familyName).to.equal('DejaVu Sans'); } // I think this depends on the distro? We don't specify a default. }); ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () { const html = ` <html lang="ja-JP"> <head> <meta charset="utf-8" /> </head> <body style="font-family: sans-serif">test 智史</body> </html> `; const fonts = await getRenderedFonts(html); expect(fonts).to.be.an('array'); expect(fonts).to.have.length(1); if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); } }); }); describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => { const fullscreenChildHtml = promisify(fs.readFile)( path.join(fixturesPath, 'pages', 'fullscreen-oopif.html') ); let w: BrowserWindow; let server: http.Server; let crossSiteUrl: string; beforeEach(async () => { server = http.createServer(async (_req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(await fullscreenChildHtml); res.end(); }); const serverUrl = (await listen(server)).url; crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost'); w = new BrowserWindow({ show: true, fullscreen: true, webPreferences: { nodeIntegration: true, nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); afterEach(async () => { await closeAllWindows(); (w as any) = null; server.close(); }); ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => { const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await setTimeout(500); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => { await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); const html = `<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`; w.loadURL(`data:text/html,${html}`); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.be.true(); await w.webContents.executeJavaScript( "document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')" ); await once(w.webContents, 'leave-html-full-screen'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); w.setFullScreen(false); await once(w, 'leave-full-screen'); }); // TODO(jkleinsc) fix this flaky test on WOA ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => { if (process.platform === 'darwin') await once(w, 'enter-full-screen'); const fullscreenChange = once(ipcMain, 'fullscreenChange'); w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html')); await fullscreenChange; const fullscreenWidth = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(fullscreenWidth > 0).to.true(); await w.webContents.executeJavaScript('document.exitFullscreen()'); const width = await w.webContents.executeJavaScript( "document.querySelector('iframe').offsetWidth" ); expect(width).to.equal(0); }); }); describe('navigator.serial', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const getPorts: any = () => { return w.webContents.executeJavaScript(` navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.'; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.removeAllListeners('select-serial-port'); }); it('does not return a port if select-serial-port event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not return a port when permission denied', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback(portList[0].portId); }); session.defaultSession.setPermissionCheckHandler(() => false); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('does not crash when select-serial-port is called with an invalid port', async () => { w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { callback('i-do-not-exist'); }); const port = await getPorts(); expect(port).to.equal(notFoundError); }); it('returns a port when select-serial-port event is defined', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); const port = await getPorts(); if (havePorts) { expect(port).to.equal('[object SerialPort]'); } else { expect(port).to.equal(notFoundError); } }); it('navigator.serial.getPorts() returns values', async () => { let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts).to.not.be.empty(); } }); it('supports port.forget()', async () => { let forgottenPortFromEvent = {}; let havePorts = false; w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { if (portList.length > 0) { havePorts = true; callback(portList[0].portId); } else { callback(''); } }); w.webContents.session.on('serial-port-revoked', (event, details) => { forgottenPortFromEvent = details.port; }); await getPorts(); if (havePorts) { const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); if (grantedPorts.length > 0) { const forgottenPort = await w.webContents.executeJavaScript(` navigator.serial.getPorts().then(async(ports) => { const portInfo = await ports[0].getInfo(); await ports[0].forget(); if (portInfo.usbVendorId && portInfo.usbProductId) { return { vendorId: '' + portInfo.usbVendorId, productId: '' + portInfo.usbProductId } } else { return {}; } }) `); const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); if (forgottenPort.vendorId && forgottenPort.productId) { expect(forgottenPortFromEvent).to.include(forgottenPort); } } } }); }); describe('window.getScreenDetails', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); const getScreenDetails: any = () => { return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true); }; it('returns screens when a PermissionRequestHandler is not defined', async () => { const screens = await getScreenDetails(); expect(screens).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(false); } else { callback(true); } }); const screens = await getScreenDetails(); expect(screens).to.equal('Permission denied.'); }); it('returns screens when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'window-management') { callback(true); } else { callback(false); } }); const screens = await getScreenDetails(); expect(screens).to.not.equal('Permission denied.'); }); }); describe('navigator.clipboard.read', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const readClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(false); } else { callback(true); } }); const clipboard = await readClipboard(); expect(clipboard).to.equal('Read permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-read') { callback(true); } else { callback(false); } }); const clipboard = await readClipboard(); expect(clipboard).to.not.equal('Read permission denied.'); }); }); describe('navigator.clipboard.write', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow(); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); const writeClipboard: any = () => { return w.webContents.executeJavaScript(` navigator.clipboard.writeText('Hello World!').catch(err => err.message); `, true); }; after(closeAllWindows); afterEach(() => { session.defaultSession.setPermissionRequestHandler(null); }); it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => { const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); it('returns an error when permission denied', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(false); } else { callback(true); } }); const clipboard = await writeClipboard(); expect(clipboard).to.equal('Write permission denied.'); }); it('returns clipboard contents when permission is granted', async () => { session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => { if (permission === 'clipboard-sanitized-write') { callback(true); } else { callback(false); } }); const clipboard = await writeClipboard(); expect(clipboard).to.not.equal('Write permission denied.'); }); }); ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => { let w: BrowserWindow; const expectedBadgeCount = 42; const fireAppBadgeAction: any = (action: string, value: any) => { return w.webContents.executeJavaScript(` navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`); }; // For some reason on macOS changing the badge count doesn't happen right away, so wait // until it changes. async function waitForBadgeCount (value: number) { let badgeCount = app.getBadgeCount(); while (badgeCount !== value) { await setTimeout(10); badgeCount = app.getBadgeCount(); } return badgeCount; } describe('in the renderer', () => { before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can set a numerical value', async () => { const result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); }); it('setAppBadge can set an empty(dot) value', async () => { const result = await fireAppBadgeAction('set'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); it('clearAppBadge can clear a value', async () => { let result = await fireAppBadgeAction('set', expectedBadgeCount); expect(result).to.equal('success'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); result = await fireAppBadgeAction('clear'); expect(result).to.equal('success'); expect(waitForBadgeCount(0)).to.eventually.equal(0); }); }); describe('in a service worker', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, partition: 'sw-file-scheme-spec', contextIsolation: false } }); }); afterEach(() => { app.badgeCount = 0; closeAllWindows(); }); it('setAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' }); }); it('clearAppBadge can be called in a ServiceWorker', (done) => { w.webContents.on('ipc-message', (event, channel, message) => { if (channel === 'reload') { w.webContents.reload(); } else if (channel === 'setAppBadge') { expect(message).to.equal('SUCCESS setting app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); } else if (channel === 'error') { done(message); } else if (channel === 'response') { expect(message).to.equal('SUCCESS clearing app badge'); expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount); session.fromPartition('sw-file-scheme-spec').clearStorageData({ storages: ['serviceworkers'] }).then(() => done()); } }); w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.'))); w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' }); }); }); }); describe('navigator.bluetooth', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { enableBlinkFeatures: 'WebBluetooth' } }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); }); after(closeAllWindows); it('can request bluetooth devices', async () => { const bluetooth = await w.webContents.executeJavaScript(` navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true); expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']); }); }); describe('navigator.hid', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-hid-device'); }); it('does not return a device if select-hid-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(''); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(''); }); it('returns a device when select-hid-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); } else { expect(device).to.equal(''); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.hid.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object HIDDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(''); } }); it('excludes a device when a exclusionFilter is specified', async () => { const exclusionFilters = <any>[]; let haveDevices = false; let checkForExcludedDevice = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { details.deviceList.find((device) => { if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') { if (checkForExcludedDevice) { const compareDevice = { vendorId: device.vendorId, productId: device.productId }; expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned'); } else { haveDevices = true; exclusionFilters.push({ vendorId: device.vendorId, productId: device.productId }); return true; } } }); } callback(); }); await requestDevices(); if (haveDevices) { // We have devices to exclude, so check if exclusionFilters work checkForExcludedDevice = true; await w.webContents.executeJavaScript(` navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString()); `, true); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-hid-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('hid-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice = await w.webContents.executeJavaScript(` navigator.hid.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, name: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); }); describe('navigator.usb', () => { let w: BrowserWindow; let server: http.Server; let serverUrl: string; before(async () => { w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.end('<body>'); }); serverUrl = (await listen(server)).url; }); const requestDevices: any = () => { return w.webContents.executeJavaScript(` navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString()); `, true); }; const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.'; after(() => { server.close(); closeAllWindows(); }); afterEach(() => { session.defaultSession.setPermissionCheckHandler(null); session.defaultSession.setDevicePermissionHandler(null); session.defaultSession.removeAllListeners('select-usb-device'); }); it('does not return a device if select-usb-device event is not defined', async () => { w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); const device = await requestDevices(); expect(device).to.equal(notFoundError); }); it('does not return a device when permission denied', async () => { let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; callback(); }); session.defaultSession.setPermissionCheckHandler(() => false); const device = await requestDevices(); expect(selectFired).to.be.false(); expect(device).to.equal(notFoundError); }); it('returns a device when select-usb-device event is defined', async () => { let haveDevices = false; let selectFired = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number'); selectFired = true; if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); } else { expect(device).to.equal(notFoundError); } if (haveDevices) { // Verify that navigation will clear device permissions const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices).to.not.be.empty(); w.loadURL(serverUrl); const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate'); const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(!!frame).to.be.true(); if (frame) { const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevicesOnNewPage).to.be.empty(); } } }); it('returns a device when DevicePermissionHandler is defined', async () => { let haveDevices = false; let selectFired = false; let gotDevicePerms = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { selectFired = true; if (details.deviceList.length > 0) { const foundDevice = details.deviceList.find((device) => { if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') { haveDevices = true; return true; } }); if (foundDevice) { callback(foundDevice.deviceId); return; } } callback(); }); session.defaultSession.setDevicePermissionHandler(() => { gotDevicePerms = true; return true; }); await w.webContents.executeJavaScript('navigator.usb.getDevices();', true); const device = await requestDevices(); expect(selectFired).to.be.true(); if (haveDevices) { expect(device).to.contain('[object USBDevice]'); expect(gotDevicePerms).to.be.true(); } else { expect(device).to.equal(notFoundError); } }); it('supports device.forget()', async () => { let deletedDeviceFromEvent; let haveDevices = false; w.webContents.session.on('select-usb-device', (event, details, callback) => { if (details.deviceList.length > 0) { haveDevices = true; callback(details.deviceList[0].deviceId); } else { callback(); } }); w.webContents.session.on('usb-device-revoked', (event, details) => { deletedDeviceFromEvent = details.device; }); await requestDevices(); if (haveDevices) { const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); if (grantedDevices.length > 0) { const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(` navigator.usb.getDevices().then(devices => { devices[0].forget(); return { vendorId: devices[0].vendorId, productId: devices[0].productId, productName: devices[0].productName } }) `); const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()'); expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length); if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) { expect(deletedDeviceFromEvent).to.include(deletedDevice); } } } }); });
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
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 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 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 add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.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 add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_crash_on_nativetheme_change_during_context_menu_close.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
patches/chromium/fix_use_delegated_generic_capturer_when_available.patch
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; DesktopCapturer::DesktopListListener::DesktopListListener( OnceCallback update_callback, OnceCallback failure_callback, bool skip_thumbnails) : update_callback_(std::move(update_callback)), failure_callback_(std::move(failure_callback)), have_thumbnail_(skip_thumbnails) {} DesktopCapturer::DesktopListListener::~DesktopListListener() = default; void DesktopCapturer::DesktopListListener::OnDelegatedSourceListSelection() { if (have_thumbnail_) { std::move(update_callback_).Run(); } else { have_selection_ = true; } } void DesktopCapturer::DesktopListListener::OnSourceThumbnailChanged(int index) { if (have_selection_) { // This is called every time a thumbnail is refreshed. Reset variable to // ensure that the callback is not run again. have_selection_ = false; // PipeWire returns a single source, so index is not relevant. std::move(update_callback_).Run(); } else { have_thumbnail_ = true; } } void DesktopCapturer::DesktopListListener::OnDelegatedSourceListDismissed() { std::move(failure_callback_).Run(); } void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); if (window_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); } else { window_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()); if (screen_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); screen_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); screen_capturer_->StartUpdating(screen_listener_.get()); } else { screen_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { HandleFailure(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } void DesktopCapturer::HandleFailure() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
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 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 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 add_electron_deps_to_license_credits_file.patch fix_crash_loading_non-standard_schemes_in_iframes.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 add_gin_converter_support_for_arraybufferview.patch chore_defer_usb_service_getdevices_request_until_usb_service_is.patch fix_remove_profiles_from_spellcheck_service.patch chore_patch_out_profile_methods_in_chrome_browser_pdf.patch chore_patch_out_profile_methods_in_titlebar_config.patch fix_crash_on_nativetheme_change_during_context_menu_close.patch fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
patches/chromium/fix_use_delegated_generic_capturer_when_available.patch
closed
electron/electron
https://github.com/electron/electron
39,043
[Feature Request]: Use combined PipeWire Picker for desktopCapturer when windows and screens are requested
### 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 When calling `desktopCapturer.getSources({ types: ['window', 'screen'] })` it opens two PipeWire pickers, one for a window and one for a screen. It can't get the sources if one of them is canceled (e.g. the user only wants to share a window or screen and cancels the other one). ![image](https://github.com/electron/electron/assets/32410361/db11fb32-7c77-4d8f-980d-9251ba587254) ### Proposed Solution Use a combined picker if a window and screen capture is requested. My Pseudo Idea how this could be implemented: Add a check in [electron_api_desktop_capturer.cc](https://github.com/aiddya/electron/blob/72f357ad773056483518964820700672465a048f/shell/browser/api/electron_api_desktop_capturer.cc#L240) if capture_window and capture_screen are true and a delegated Sourcelist is used. Then somehow pass `ScreenCastPortal::CaptureSourceType::kAnyScreenContent` as a CaptureType in [screencast_portal.cc](https://webrtc.googlesource.com/src/+/8fcc6df79daf1810cd4ecdb8d2ef1d361abfdc9c/modules/desktop_capture/linux/wayland/screencast_portal.cc#95) ### Alternatives Considered Ignore if one of the pickers gets canceled. ### Additional Information Fixing behavior that was out of scope of #38833
https://github.com/electron/electron/issues/39043
https://github.com/electron/electron/pull/39111
a83f9c06d701f1126eaf8da605e27125c90edb87
9cd5de75888d67b20bb7faf59ca4272323895c62
2023-07-10T20:38:37Z
c++
2023-07-21T23:03:01Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; DesktopCapturer::DesktopListListener::DesktopListListener( OnceCallback update_callback, OnceCallback failure_callback, bool skip_thumbnails) : update_callback_(std::move(update_callback)), failure_callback_(std::move(failure_callback)), have_thumbnail_(skip_thumbnails) {} DesktopCapturer::DesktopListListener::~DesktopListListener() = default; void DesktopCapturer::DesktopListListener::OnDelegatedSourceListSelection() { if (have_thumbnail_) { std::move(update_callback_).Run(); } else { have_selection_ = true; } } void DesktopCapturer::DesktopListListener::OnSourceThumbnailChanged(int index) { if (have_selection_) { // This is called every time a thumbnail is refreshed. Reset variable to // ensure that the callback is not run again. have_selection_ = false; // PipeWire returns a single source, so index is not relevant. std::move(update_callback_).Run(); } else { have_thumbnail_ = true; } } void DesktopCapturer::DesktopListListener::OnDelegatedSourceListDismissed() { std::move(failure_callback_).Run(); } void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); if (window_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); } else { window_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()); if (screen_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); screen_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); screen_capturer_->StartUpdating(screen_listener_.get()); } else { screen_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { HandleFailure(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } void DesktopCapturer::HandleFailure() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,186
Releases page: node version missing for electron 25
there is already a stable release for electron 25 with node 18.15.0: https://releases.electronjs.org/release/v25.3.1 But this releases list is missing the node version ("TBD") for electron 25. https://www.electronjs.org/docs/latest/tutorial/electron-timelines
https://github.com/electron/electron/issues/39186
https://github.com/electron/electron/pull/39187
2c52eb7e1c61aa1ae5e91b4ad062dc7d67fb764e
1ca3a7d3c988b671d0ebe5f3b62b4890da9faacf
2023-07-21T07:57:45Z
c++
2023-07-24T10:33:10Z
docs/tutorial/electron-timelines.md
# Electron Releases Electron frequently releases major versions alongside every other Chromium release. This document focuses on the release cadence and version support policy. For a more in-depth guide on our git branches and how Electron uses semantic versions, check out our [Electron Versioning](./electron-versioning.md) doc. ## Timeline | Electron | Alpha | Beta | Stable | EOL | Chrome | Node | Supported | | ------- | ----- | ------- | ------ | ------ | ---- | ---- | ---- | | 26.0.0 | 2023-Jun-01 | 2023-Jun-27 | 2023-Aug-15 | TBD | M116 | TBD | ✅ | | 25.0.0 | 2023-Apr-10 | 2023-May-02 | 2023-May-30 | 2024-Jan-02 | M114 | TBD | ✅ | | 24.0.0 | 2022-Feb-09 | 2023-Mar-07 | 2023-Apr-04 | 2023-Oct-10 | M112 | v18.14 | ✅ | | 23.0.0 | 2022-Dec-01 | 2023-Jan-10 | 2023-Feb-07 | 2023-Aug-15 | M110 | v18.12 | ✅ | | 22.0.0 | 2022-Sep-29 | 2022-Oct-25 | 2022-Nov-29 | 2023-Oct-10 | M108 | v16.17 | ✅ | | 21.0.0 | 2022-Aug-04 | 2022-Aug-30 | 2022-Sep-27 | 2023-Apr-04 | M106 | v16.16 | 🚫 | | 20.0.0 | 2022-May-26 | 2022-Jun-21 | 2022-Aug-02 | 2023-Feb-07 | M104 | v16.15 | 🚫 | | 19.0.0 | 2022-Mar-31 | 2022-Apr-26 | 2022-May-24 | 2022-Nov-29 | M102 | v16.14 | 🚫 | | 18.0.0 | 2022-Feb-03 | 2022-Mar-03 | 2022-Mar-29 | 2022-Sep-27 | M100 | v16.13 | 🚫 | | 17.0.0 | 2021-Nov-18 | 2022-Jan-06 | 2022-Feb-01 | 2022-Aug-02 | M98 | v16.13 | 🚫 | | 16.0.0 | 2021-Sep-23 | 2021-Oct-20 | 2021-Nov-16 | 2022-May-24 | M96 | v16.9 | 🚫 | | 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | 2022-May-24 | M94 | v16.5 | 🚫 | | 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | 2022-Mar-29 | M93 | v14.17 | 🚫 | | 13.0.0 | -- | 2021-Mar-04 | 2021-May-25 | 2022-Feb-01 | M91 | v14.16 | 🚫 | | 12.0.0 | -- | 2020-Nov-19 | 2021-Mar-02 | 2021-Nov-16 | M89 | v14.16 | 🚫 | | 11.0.0 | -- | 2020-Aug-27 | 2020-Nov-17 | 2021-Aug-31 | M87 | v12.18 | 🚫 | | 10.0.0 | -- | 2020-May-21 | 2020-Aug-25 | 2021-May-25 | M85 | v12.16 | 🚫 | | 9.0.0 | -- | 2020-Feb-06 | 2020-May-19 | 2021-Mar-02 | M83 | v12.14 | 🚫 | | 8.0.0 | -- | 2019-Oct-24 | 2020-Feb-04 | 2020-Nov-17 | M80 | v12.13 | 🚫 | | 7.0.0 | -- | 2019-Aug-01 | 2019-Oct-22 | 2020-Aug-25 | M78 | v12.8 | 🚫 | | 6.0.0 | -- | 2019-Apr-25 | 2019-Jul-30 | 2020-May-19 | M76 | v12.14.0 | 🚫 | | 5.0.0 | -- | 2019-Jan-22 | 2019-Apr-23 | 2020-Feb-04 | M73 | v12.0 | 🚫 | | 4.0.0 | -- | 2018-Oct-11 | 2018-Dec-20 | 2019-Oct-22 | M69 | v10.11 | 🚫 | | 3.0.0 | -- | 2018-Jun-21 | 2018-Sep-18 | 2019-Jul-30 | M66 | v10.2 | 🚫 | | 2.0.0 | -- | 2018-Feb-21 | 2018-May-01 | 2019-Apr-23 | M61 | v8.9 | 🚫 | **Notes:** * The `-alpha.1`, `-beta.1`, and `stable` dates are our solid release dates. * We strive for weekly alpha/beta releases, but we often release more than scheduled. * All dates are our goals but there may be reasons for adjusting the stable deadline, such as security bugs. **Historical changes:** * Since Electron 5, Electron has been publicizing its release dates ([see blog post](https://electronjs.org/blog/electron-5-0-timeline)). * Since Electron 6, Electron major versions have been targeting every other Chromium major version. Each Electron stable should happen on the same day as Chrome stable ([see blog post](https://www.electronjs.org/blog/12-week-cadence)). * Since Electron 16, Electron has been releasing major versions on an 8-week cadence in accordance to Chrome's change to a 4-week release cadence ([see blog post](https://www.electronjs.org/blog/8-week-cadence)). :::info Chrome release dates Chromium has the own public release schedule [here](https://chromiumdash.appspot.com/schedule). ::: ## Version support policy :::info The Electron team will temporarily support Electron 22 until October 10, 2023. This extended support is intended to help Electron developers who still need support for Windows 7/8/8.1, which ended support in Electron 23. The October support date follows the extended support dates from both Chromium and Microsoft. On October 11, the Electron team will drop support back to the latest three stable major versions. ::: The latest three _stable_ major versions are supported by the Electron team. For example, if the latest release is 6.1.x, then the 5.0.x as well as the 4.2.x series are supported. We only support the latest minor release for each stable release series. This means that in the case of a security fix, 6.1.x will receive the fix, but we will not release a new version of 6.0.x. The latest stable release unilaterally receives all fixes from `main`, and the version prior to that receives the vast majority of those fixes as time and bandwidth warrants. The oldest supported release line will receive only security fixes directly. ### Breaking API changes When an API is changed or removed in a way that breaks existing functionality, the previous functionality will be supported for a minimum of two major versions when possible before being removed. For example, if a function takes three arguments, and that number is reduced to two in major version 10, the three-argument version would continue to work until, at minimum, major version 12. Past the minimum two-version threshold, we will attempt to support backwards compatibility beyond two versions until the maintainers feel the maintenance burden is too high to continue doing so. ### End-of-life When a release branch reaches the end of its support cycle, the series will be deprecated in NPM and a final end-of-support release will be made. This release will add a warning to inform that an unsupported version of Electron is in use. These steps are to help app developers learn when a branch they're using becomes unsupported, but without being excessively intrusive to end users. If an application has exceptional circumstances and needs to stay on an unsupported series of Electron, developers can silence the end-of-support warning by omitting the final release from the app's `package.json` `devDependencies`. For example, since the 1-6-x series ended with an end-of-support 1.6.18 release, developers could choose to stay in the 1-6-x series without warnings with `devDependency` of `"electron": 1.6.0 - 1.6.17`.
closed
electron/electron
https://github.com/electron/electron
39,186
Releases page: node version missing for electron 25
there is already a stable release for electron 25 with node 18.15.0: https://releases.electronjs.org/release/v25.3.1 But this releases list is missing the node version ("TBD") for electron 25. https://www.electronjs.org/docs/latest/tutorial/electron-timelines
https://github.com/electron/electron/issues/39186
https://github.com/electron/electron/pull/39187
2c52eb7e1c61aa1ae5e91b4ad062dc7d67fb764e
1ca3a7d3c988b671d0ebe5f3b62b4890da9faacf
2023-07-21T07:57:45Z
c++
2023-07-24T10:33:10Z
docs/tutorial/electron-timelines.md
# Electron Releases Electron frequently releases major versions alongside every other Chromium release. This document focuses on the release cadence and version support policy. For a more in-depth guide on our git branches and how Electron uses semantic versions, check out our [Electron Versioning](./electron-versioning.md) doc. ## Timeline | Electron | Alpha | Beta | Stable | EOL | Chrome | Node | Supported | | ------- | ----- | ------- | ------ | ------ | ---- | ---- | ---- | | 26.0.0 | 2023-Jun-01 | 2023-Jun-27 | 2023-Aug-15 | TBD | M116 | TBD | ✅ | | 25.0.0 | 2023-Apr-10 | 2023-May-02 | 2023-May-30 | 2024-Jan-02 | M114 | TBD | ✅ | | 24.0.0 | 2022-Feb-09 | 2023-Mar-07 | 2023-Apr-04 | 2023-Oct-10 | M112 | v18.14 | ✅ | | 23.0.0 | 2022-Dec-01 | 2023-Jan-10 | 2023-Feb-07 | 2023-Aug-15 | M110 | v18.12 | ✅ | | 22.0.0 | 2022-Sep-29 | 2022-Oct-25 | 2022-Nov-29 | 2023-Oct-10 | M108 | v16.17 | ✅ | | 21.0.0 | 2022-Aug-04 | 2022-Aug-30 | 2022-Sep-27 | 2023-Apr-04 | M106 | v16.16 | 🚫 | | 20.0.0 | 2022-May-26 | 2022-Jun-21 | 2022-Aug-02 | 2023-Feb-07 | M104 | v16.15 | 🚫 | | 19.0.0 | 2022-Mar-31 | 2022-Apr-26 | 2022-May-24 | 2022-Nov-29 | M102 | v16.14 | 🚫 | | 18.0.0 | 2022-Feb-03 | 2022-Mar-03 | 2022-Mar-29 | 2022-Sep-27 | M100 | v16.13 | 🚫 | | 17.0.0 | 2021-Nov-18 | 2022-Jan-06 | 2022-Feb-01 | 2022-Aug-02 | M98 | v16.13 | 🚫 | | 16.0.0 | 2021-Sep-23 | 2021-Oct-20 | 2021-Nov-16 | 2022-May-24 | M96 | v16.9 | 🚫 | | 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | 2022-May-24 | M94 | v16.5 | 🚫 | | 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | 2022-Mar-29 | M93 | v14.17 | 🚫 | | 13.0.0 | -- | 2021-Mar-04 | 2021-May-25 | 2022-Feb-01 | M91 | v14.16 | 🚫 | | 12.0.0 | -- | 2020-Nov-19 | 2021-Mar-02 | 2021-Nov-16 | M89 | v14.16 | 🚫 | | 11.0.0 | -- | 2020-Aug-27 | 2020-Nov-17 | 2021-Aug-31 | M87 | v12.18 | 🚫 | | 10.0.0 | -- | 2020-May-21 | 2020-Aug-25 | 2021-May-25 | M85 | v12.16 | 🚫 | | 9.0.0 | -- | 2020-Feb-06 | 2020-May-19 | 2021-Mar-02 | M83 | v12.14 | 🚫 | | 8.0.0 | -- | 2019-Oct-24 | 2020-Feb-04 | 2020-Nov-17 | M80 | v12.13 | 🚫 | | 7.0.0 | -- | 2019-Aug-01 | 2019-Oct-22 | 2020-Aug-25 | M78 | v12.8 | 🚫 | | 6.0.0 | -- | 2019-Apr-25 | 2019-Jul-30 | 2020-May-19 | M76 | v12.14.0 | 🚫 | | 5.0.0 | -- | 2019-Jan-22 | 2019-Apr-23 | 2020-Feb-04 | M73 | v12.0 | 🚫 | | 4.0.0 | -- | 2018-Oct-11 | 2018-Dec-20 | 2019-Oct-22 | M69 | v10.11 | 🚫 | | 3.0.0 | -- | 2018-Jun-21 | 2018-Sep-18 | 2019-Jul-30 | M66 | v10.2 | 🚫 | | 2.0.0 | -- | 2018-Feb-21 | 2018-May-01 | 2019-Apr-23 | M61 | v8.9 | 🚫 | **Notes:** * The `-alpha.1`, `-beta.1`, and `stable` dates are our solid release dates. * We strive for weekly alpha/beta releases, but we often release more than scheduled. * All dates are our goals but there may be reasons for adjusting the stable deadline, such as security bugs. **Historical changes:** * Since Electron 5, Electron has been publicizing its release dates ([see blog post](https://electronjs.org/blog/electron-5-0-timeline)). * Since Electron 6, Electron major versions have been targeting every other Chromium major version. Each Electron stable should happen on the same day as Chrome stable ([see blog post](https://www.electronjs.org/blog/12-week-cadence)). * Since Electron 16, Electron has been releasing major versions on an 8-week cadence in accordance to Chrome's change to a 4-week release cadence ([see blog post](https://www.electronjs.org/blog/8-week-cadence)). :::info Chrome release dates Chromium has the own public release schedule [here](https://chromiumdash.appspot.com/schedule). ::: ## Version support policy :::info The Electron team will temporarily support Electron 22 until October 10, 2023. This extended support is intended to help Electron developers who still need support for Windows 7/8/8.1, which ended support in Electron 23. The October support date follows the extended support dates from both Chromium and Microsoft. On October 11, the Electron team will drop support back to the latest three stable major versions. ::: The latest three _stable_ major versions are supported by the Electron team. For example, if the latest release is 6.1.x, then the 5.0.x as well as the 4.2.x series are supported. We only support the latest minor release for each stable release series. This means that in the case of a security fix, 6.1.x will receive the fix, but we will not release a new version of 6.0.x. The latest stable release unilaterally receives all fixes from `main`, and the version prior to that receives the vast majority of those fixes as time and bandwidth warrants. The oldest supported release line will receive only security fixes directly. ### Breaking API changes When an API is changed or removed in a way that breaks existing functionality, the previous functionality will be supported for a minimum of two major versions when possible before being removed. For example, if a function takes three arguments, and that number is reduced to two in major version 10, the three-argument version would continue to work until, at minimum, major version 12. Past the minimum two-version threshold, we will attempt to support backwards compatibility beyond two versions until the maintainers feel the maintenance burden is too high to continue doing so. ### End-of-life When a release branch reaches the end of its support cycle, the series will be deprecated in NPM and a final end-of-support release will be made. This release will add a warning to inform that an unsupported version of Electron is in use. These steps are to help app developers learn when a branch they're using becomes unsupported, but without being excessively intrusive to end users. If an application has exceptional circumstances and needs to stay on an unsupported series of Electron, developers can silence the end-of-support warning by omitting the final release from the app's `package.json` `devDependencies`. For example, since the 1-6-x series ended with an end-of-support 1.6.18 release, developers could choose to stay in the 1-6-x series without warnings with `devDependency` of `"electron": 1.6.0 - 1.6.17`.
closed
electron/electron
https://github.com/electron/electron
39,077
[Bug]: Non-resizable windows can still be maximized on Macs the first time
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if I set `resizable:false` on a `BrowserWindow`, I won't be able to maximize/fullscreen it. ### Actual Behavior The green maximize button is enabled and I can maximized. When I click it again however and the window restores to the normal size, then it becomes disabled. ### Testcase Gist URL https://gist.github.com/pushkin-/67fb41db75da3eb6dbaa34d39d34fabf ### Additional Information Start the gist, maximize the window, unmaximize it, notice the green maximize button is now correctly disabled. I also get a bunch of logs in the console when I fullscreen the window for some reason: ``` 1 HIToolbox 0x000000018c4905c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120 2 HIToolbox 0x000000018c490188 _ZN15MenuBarInstance14EnableAutoShowEv + 60 3 HIToolbox 0x000000018c3fd8bc _ZN15MenuBarInstance21UpdateAggregateUIModeE21MenuBarAnimationStylehhh + 1184 4 HIToolbox 0x000000018c490004 _ZN15MenuBarInstance19SetFullScreenUIModeEjj + 180 5 AppKit 0x000000018627fd30 -[NSApplication _setPresentationOptions:instance:flags:] + 956 6 AppKit 0x000000018611593c -[NSApplication _updateFullScreenPresentationOptionsForInstance:] + 404 7 CoreFoundation 0x0000000182d32560 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 8 CoreFoundation 0x0000000182dd0044 ___CFXRegistrationPost_block_invoke + 88 9 CoreFoundation 0x0000000182dcff8c _CFXRegistrationPost + 440 10 CoreFoundation 0x0000000182d03b64 _CFXNotificationPost + 708 11 Foundation 0x0000000183bf338c -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 12 AppKit 0x00000001862802b4 spacesNotificationHandler + 96 13 SkyLight 0x000000018796d214 _ZN12_GLOBAL__N_123notify_datagram_handlerEj15CGSDatagramTypePvmS1_ + 896 14 SkyLight 0x0000000187c994d4 _ZN21CGSDatagramReadStream26dispatchMainQueueDatagramsEv + 228 15 SkyLight 0x0000000187c993d0 ___ZN21CGSDatagramReadStream15mainQueueWakeupEv_block_invoke + 28 16 libdispatch.dylib 0x0000000182ad49dc _dispatch_call_block_and_release + 32 17 libdispatch.dylib 0x0000000182ad6504 _dispatch_client_callout + 20 18 libdispatch.dylib 0x0000000182ae4d1c _dispatch_main_queue_drain + 928 19 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 22 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 23 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 24 HIToolbox 0x000000018c41bde4 ReceiveNextEventCommon + 672 25 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 26 AppKit 0x0000000185fc184c _DPSNextEvent + 632 27 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 28 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 29 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 30 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 31 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 32 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 33 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 34 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 35 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 36 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 37 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 38 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 39 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 40 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 41 Electron Framework 0x000000010acd91d8 ElectronMain + 128 42 dyld 0x0000000182933e50 start + 2544 1 HIToolbox 0x000000018c41b90c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44 2 HIToolbox 0x000000018c490fbc _ZN15MenuBarInstance15DisableAutoShowEv + 36 3 HIToolbox 0x000000018c4910b0 _ZN15MenuBarInstanceD2Ev + 128 4 HIToolbox 0x000000018c490ee0 _ZN15MenuBarInstance7ReleaseEv + 56 5 AppKit 0x000000018661d4dc -[NSHIPresentationInstance discard] + 228 6 AppKit 0x00000001869dc8b4 -[_NSFullScreenSpace(PresentationInstance) discardPresentationInstance] + 32 7 AppKit 0x00000001869dc90c -[_NSFullScreenSpace(PresentationInstance) activateFullScreenPresentationOptions] + 64 8 AppKit 0x0000000186836968 -[_NSExitFullScreenTransitionController _doSucceededToExitFullScreen] + 40 9 AppKit 0x0000000186837440 __63-[_NSExitFullScreenTransitionController _performExitFullScreen]_block_invoke + 236 10 libxpc.dylib 0x00000001829ce42c _xpc_connection_reply_callout + 124 11 libxpc.dylib 0x00000001829ce31c _xpc_connection_call_reply_async + 88 12 libdispatch.dylib 0x0000000182ad6584 _dispatch_client_callout3 + 20 13 libdispatch.dylib 0x0000000182af4710 _dispatch_mach_msg_async_reply_invoke + 344 14 libdispatch.dylib 0x0000000182ae4c70 _dispatch_main_queue_drain + 756 15 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 16 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 17 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 18 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 19 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 20 HIToolbox 0x000000018c41bc30 ReceiveNextEventCommon + 236 21 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 22 AppKit 0x0000000185fc184c _DPSNextEvent + 632 23 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 24 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 25 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 26 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 27 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 28 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 29 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 30 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 31 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 32 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 33 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 34 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 35 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 36 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 37 Electron Framework 0x000000010acd91d8 ElectronMain + 128 38 dyld 0x0000000182933e50 start + 2544 ```
https://github.com/electron/electron/issues/39077
https://github.com/electron/electron/pull/39086
455f57322f705fdd67751328e8f1feaf6bd29409
12548294c0b2639d34c05c544f56545004efee01
2023-07-12T20:04:56Z
c++
2023-07-25T16:18:36Z
shell/browser/native_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/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #elif BUILDFLAG(IS_WIN) std::string material; if (options.Get(options::kBackgroundMaterial, &material)) { SetBackgroundMaterial(material); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { size_constraints_ = window_constraints; content_size_constraints_.reset(); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { if (size_constraints_) return *size_constraints_; if (!content_size_constraints_) return extensions::SizeConstraints(); // Convert content size constraints to window size constraints. extensions::SizeConstraints constraints; if (content_size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (content_size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { content_size_constraints_ = size_constraints; size_constraints_.reset(); } // The return value of GetContentSizeConstraints will be passed to Chromium // to set min/max sizes of window. Note that we are returning content size // instead of window size because that is what Chromium expects, see the // comment of |WidgetSizeIsClientSize| in Chromium's codebase to learn more. extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); // Convert window size constraints to content size constraints. // Note that we are not caching the results, because Chromium reccalculates // window frame size everytime when min/max sizes are passed, and we must // do the same otherwise the resulting size with frame included will be wrong. extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::ShowAllTabs() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetBackgroundMaterial(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (!base::Contains(draggable_region_providers_, provider)) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,077
[Bug]: Non-resizable windows can still be maximized on Macs the first time
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if I set `resizable:false` on a `BrowserWindow`, I won't be able to maximize/fullscreen it. ### Actual Behavior The green maximize button is enabled and I can maximized. When I click it again however and the window restores to the normal size, then it becomes disabled. ### Testcase Gist URL https://gist.github.com/pushkin-/67fb41db75da3eb6dbaa34d39d34fabf ### Additional Information Start the gist, maximize the window, unmaximize it, notice the green maximize button is now correctly disabled. I also get a bunch of logs in the console when I fullscreen the window for some reason: ``` 1 HIToolbox 0x000000018c4905c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120 2 HIToolbox 0x000000018c490188 _ZN15MenuBarInstance14EnableAutoShowEv + 60 3 HIToolbox 0x000000018c3fd8bc _ZN15MenuBarInstance21UpdateAggregateUIModeE21MenuBarAnimationStylehhh + 1184 4 HIToolbox 0x000000018c490004 _ZN15MenuBarInstance19SetFullScreenUIModeEjj + 180 5 AppKit 0x000000018627fd30 -[NSApplication _setPresentationOptions:instance:flags:] + 956 6 AppKit 0x000000018611593c -[NSApplication _updateFullScreenPresentationOptionsForInstance:] + 404 7 CoreFoundation 0x0000000182d32560 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 8 CoreFoundation 0x0000000182dd0044 ___CFXRegistrationPost_block_invoke + 88 9 CoreFoundation 0x0000000182dcff8c _CFXRegistrationPost + 440 10 CoreFoundation 0x0000000182d03b64 _CFXNotificationPost + 708 11 Foundation 0x0000000183bf338c -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 12 AppKit 0x00000001862802b4 spacesNotificationHandler + 96 13 SkyLight 0x000000018796d214 _ZN12_GLOBAL__N_123notify_datagram_handlerEj15CGSDatagramTypePvmS1_ + 896 14 SkyLight 0x0000000187c994d4 _ZN21CGSDatagramReadStream26dispatchMainQueueDatagramsEv + 228 15 SkyLight 0x0000000187c993d0 ___ZN21CGSDatagramReadStream15mainQueueWakeupEv_block_invoke + 28 16 libdispatch.dylib 0x0000000182ad49dc _dispatch_call_block_and_release + 32 17 libdispatch.dylib 0x0000000182ad6504 _dispatch_client_callout + 20 18 libdispatch.dylib 0x0000000182ae4d1c _dispatch_main_queue_drain + 928 19 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 22 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 23 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 24 HIToolbox 0x000000018c41bde4 ReceiveNextEventCommon + 672 25 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 26 AppKit 0x0000000185fc184c _DPSNextEvent + 632 27 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 28 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 29 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 30 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 31 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 32 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 33 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 34 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 35 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 36 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 37 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 38 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 39 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 40 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 41 Electron Framework 0x000000010acd91d8 ElectronMain + 128 42 dyld 0x0000000182933e50 start + 2544 1 HIToolbox 0x000000018c41b90c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44 2 HIToolbox 0x000000018c490fbc _ZN15MenuBarInstance15DisableAutoShowEv + 36 3 HIToolbox 0x000000018c4910b0 _ZN15MenuBarInstanceD2Ev + 128 4 HIToolbox 0x000000018c490ee0 _ZN15MenuBarInstance7ReleaseEv + 56 5 AppKit 0x000000018661d4dc -[NSHIPresentationInstance discard] + 228 6 AppKit 0x00000001869dc8b4 -[_NSFullScreenSpace(PresentationInstance) discardPresentationInstance] + 32 7 AppKit 0x00000001869dc90c -[_NSFullScreenSpace(PresentationInstance) activateFullScreenPresentationOptions] + 64 8 AppKit 0x0000000186836968 -[_NSExitFullScreenTransitionController _doSucceededToExitFullScreen] + 40 9 AppKit 0x0000000186837440 __63-[_NSExitFullScreenTransitionController _performExitFullScreen]_block_invoke + 236 10 libxpc.dylib 0x00000001829ce42c _xpc_connection_reply_callout + 124 11 libxpc.dylib 0x00000001829ce31c _xpc_connection_call_reply_async + 88 12 libdispatch.dylib 0x0000000182ad6584 _dispatch_client_callout3 + 20 13 libdispatch.dylib 0x0000000182af4710 _dispatch_mach_msg_async_reply_invoke + 344 14 libdispatch.dylib 0x0000000182ae4c70 _dispatch_main_queue_drain + 756 15 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 16 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 17 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 18 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 19 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 20 HIToolbox 0x000000018c41bc30 ReceiveNextEventCommon + 236 21 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 22 AppKit 0x0000000185fc184c _DPSNextEvent + 632 23 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 24 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 25 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 26 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 27 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 28 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 29 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 30 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 31 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 32 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 33 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 34 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 35 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 36 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 37 Electron Framework 0x000000010acd91d8 ElectronMain + 128 38 dyld 0x0000000182933e50 start + 2544 ```
https://github.com/electron/electron/issues/39077
https://github.com/electron/electron/pull/39086
455f57322f705fdd67751328e8f1feaf6bd29409
12548294c0b2639d34c05c544f56545004efee01
2023-07-12T20:04:56Z
c++
2023-07-25T16:18:36Z
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/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/browser.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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) 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]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // 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_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[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_ = [[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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); [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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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]; [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]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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]]; [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_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ 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::ShowAllTabs() { [window_ toggleTabOverview: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_ = [[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()) { 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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
39,077
[Bug]: Non-resizable windows can still be maximized on Macs the first time
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if I set `resizable:false` on a `BrowserWindow`, I won't be able to maximize/fullscreen it. ### Actual Behavior The green maximize button is enabled and I can maximized. When I click it again however and the window restores to the normal size, then it becomes disabled. ### Testcase Gist URL https://gist.github.com/pushkin-/67fb41db75da3eb6dbaa34d39d34fabf ### Additional Information Start the gist, maximize the window, unmaximize it, notice the green maximize button is now correctly disabled. I also get a bunch of logs in the console when I fullscreen the window for some reason: ``` 1 HIToolbox 0x000000018c4905c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120 2 HIToolbox 0x000000018c490188 _ZN15MenuBarInstance14EnableAutoShowEv + 60 3 HIToolbox 0x000000018c3fd8bc _ZN15MenuBarInstance21UpdateAggregateUIModeE21MenuBarAnimationStylehhh + 1184 4 HIToolbox 0x000000018c490004 _ZN15MenuBarInstance19SetFullScreenUIModeEjj + 180 5 AppKit 0x000000018627fd30 -[NSApplication _setPresentationOptions:instance:flags:] + 956 6 AppKit 0x000000018611593c -[NSApplication _updateFullScreenPresentationOptionsForInstance:] + 404 7 CoreFoundation 0x0000000182d32560 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 8 CoreFoundation 0x0000000182dd0044 ___CFXRegistrationPost_block_invoke + 88 9 CoreFoundation 0x0000000182dcff8c _CFXRegistrationPost + 440 10 CoreFoundation 0x0000000182d03b64 _CFXNotificationPost + 708 11 Foundation 0x0000000183bf338c -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 12 AppKit 0x00000001862802b4 spacesNotificationHandler + 96 13 SkyLight 0x000000018796d214 _ZN12_GLOBAL__N_123notify_datagram_handlerEj15CGSDatagramTypePvmS1_ + 896 14 SkyLight 0x0000000187c994d4 _ZN21CGSDatagramReadStream26dispatchMainQueueDatagramsEv + 228 15 SkyLight 0x0000000187c993d0 ___ZN21CGSDatagramReadStream15mainQueueWakeupEv_block_invoke + 28 16 libdispatch.dylib 0x0000000182ad49dc _dispatch_call_block_and_release + 32 17 libdispatch.dylib 0x0000000182ad6504 _dispatch_client_callout + 20 18 libdispatch.dylib 0x0000000182ae4d1c _dispatch_main_queue_drain + 928 19 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 22 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 23 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 24 HIToolbox 0x000000018c41bde4 ReceiveNextEventCommon + 672 25 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 26 AppKit 0x0000000185fc184c _DPSNextEvent + 632 27 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 28 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 29 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 30 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 31 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 32 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 33 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 34 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 35 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 36 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 37 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 38 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 39 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 40 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 41 Electron Framework 0x000000010acd91d8 ElectronMain + 128 42 dyld 0x0000000182933e50 start + 2544 1 HIToolbox 0x000000018c41b90c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44 2 HIToolbox 0x000000018c490fbc _ZN15MenuBarInstance15DisableAutoShowEv + 36 3 HIToolbox 0x000000018c4910b0 _ZN15MenuBarInstanceD2Ev + 128 4 HIToolbox 0x000000018c490ee0 _ZN15MenuBarInstance7ReleaseEv + 56 5 AppKit 0x000000018661d4dc -[NSHIPresentationInstance discard] + 228 6 AppKit 0x00000001869dc8b4 -[_NSFullScreenSpace(PresentationInstance) discardPresentationInstance] + 32 7 AppKit 0x00000001869dc90c -[_NSFullScreenSpace(PresentationInstance) activateFullScreenPresentationOptions] + 64 8 AppKit 0x0000000186836968 -[_NSExitFullScreenTransitionController _doSucceededToExitFullScreen] + 40 9 AppKit 0x0000000186837440 __63-[_NSExitFullScreenTransitionController _performExitFullScreen]_block_invoke + 236 10 libxpc.dylib 0x00000001829ce42c _xpc_connection_reply_callout + 124 11 libxpc.dylib 0x00000001829ce31c _xpc_connection_call_reply_async + 88 12 libdispatch.dylib 0x0000000182ad6584 _dispatch_client_callout3 + 20 13 libdispatch.dylib 0x0000000182af4710 _dispatch_mach_msg_async_reply_invoke + 344 14 libdispatch.dylib 0x0000000182ae4c70 _dispatch_main_queue_drain + 756 15 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 16 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 17 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 18 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 19 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 20 HIToolbox 0x000000018c41bc30 ReceiveNextEventCommon + 236 21 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 22 AppKit 0x0000000185fc184c _DPSNextEvent + 632 23 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 24 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 25 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 26 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 27 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 28 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 29 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 30 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 31 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 32 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 33 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 34 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 35 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 36 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 37 Electron Framework 0x000000010acd91d8 ElectronMain + 128 38 dyld 0x0000000182933e50 start + 2544 ```
https://github.com/electron/electron/issues/39077
https://github.com/electron/electron/pull/39086
455f57322f705fdd67751328e8f1feaf6bd29409
12548294c0b2639d34c05c544f56545004efee01
2023-07-12T20:04:56Z
c++
2023-07-25T16:18:36Z
shell/browser/native_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/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/base/hit_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_MAC) #include "shell/browser/ui/views/frameless_view.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay_dict = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict); int height; if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); gfx::Size max_size = size_constraints.GetMaximumSize(); int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX; int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX; bool have_max_width = options.Get(options::kMaxWidth, &max_width); if (have_max_width && max_width <= 0) max_width = INT_MAX; bool have_max_height = options.Get(options::kMaxHeight, &max_height); if (have_max_height && max_height <= 0) max_height = INT_MAX; // By default the window has a default maximum size that prevents it // from being resized larger than the screen, so we should only set this // if the user has passed in values. if (have_max_height || have_max_width || !max_size.IsEmpty()) size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #elif BUILDFLAG(IS_WIN) std::string material; if (options.Get(options::kBackgroundMaterial, &material)) { SetBackgroundMaterial(material); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseCSSColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { size_constraints_ = window_constraints; content_size_constraints_.reset(); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { if (size_constraints_) return *size_constraints_; if (!content_size_constraints_) return extensions::SizeConstraints(); // Convert content size constraints to window size constraints. extensions::SizeConstraints constraints; if (content_size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (content_size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { content_size_constraints_ = size_constraints; size_constraints_.reset(); } // The return value of GetContentSizeConstraints will be passed to Chromium // to set min/max sizes of window. Note that we are returning content size // instead of window size because that is what Chromium expects, see the // comment of |WidgetSizeIsClientSize| in Chromium's codebase to learn more. extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { if (content_size_constraints_) return *content_size_constraints_; if (!size_constraints_) return extensions::SizeConstraints(); // Convert window size constraints to content size constraints. // Note that we are not caching the results, because Chromium reccalculates // window frame size everytime when min/max sizes are passed, and we must // do the same otherwise the resulting size with frame included will be wrong. extensions::SizeConstraints constraints; if (size_constraints_->HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMaximumSize())); constraints.set_maximum_size(max_bounds.size()); } if (size_constraints_->HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(size_constraints_->GetMinimumSize())); constraints.set_minimum_size(min_bounds.size()); } return constraints; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints = GetSizeConstraints(); size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::InvalidateShadow() {} void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::ShowAllTabs() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetBackgroundMaterial(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif int NativeWindow::NonClientHitTest(const gfx::Point& point) { #if !BUILDFLAG(IS_MAC) // We need to ensure we account for resizing borders on Windows and Linux. if ((!has_frame() || has_client_frame()) && IsResizable()) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); int border_hit = frame->ResizingBorderHitTest(point); if (border_hit != HTNOWHERE) return border_hit; } #endif for (auto* provider : draggable_region_providers_) { int hit = provider->NonClientHitTest(point); if (hit != HTNOWHERE) return hit; } return HTNOWHERE; } void NativeWindow::AddDraggableRegionProvider( DraggableRegionProvider* provider) { if (!base::Contains(draggable_region_providers_, provider)) { draggable_region_providers_.push_back(provider); } } void NativeWindow::RemoveDraggableRegionProvider( DraggableRegionProvider* provider) { draggable_region_providers_.remove_if( [&provider](DraggableRegionProvider* p) { return p == provider; }); } views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } void NativeWindow::HandlePendingFullscreenTransitions() { if (pending_transitions_.empty()) { set_fullscreen_transition_type(FullScreenTransitionType::kNone); return; } bool next_transition = pending_transitions_.front(); pending_transitions_.pop(); SetFullScreen(next_transition); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
39,077
[Bug]: Non-resizable windows can still be maximized on Macs the first time
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect that if I set `resizable:false` on a `BrowserWindow`, I won't be able to maximize/fullscreen it. ### Actual Behavior The green maximize button is enabled and I can maximized. When I click it again however and the window restores to the normal size, then it becomes disabled. ### Testcase Gist URL https://gist.github.com/pushkin-/67fb41db75da3eb6dbaa34d39d34fabf ### Additional Information Start the gist, maximize the window, unmaximize it, notice the green maximize button is now correctly disabled. I also get a bunch of logs in the console when I fullscreen the window for some reason: ``` 1 HIToolbox 0x000000018c4905c8 _ZN15MenuBarInstance22EnsureAutoShowObserverEv + 120 2 HIToolbox 0x000000018c490188 _ZN15MenuBarInstance14EnableAutoShowEv + 60 3 HIToolbox 0x000000018c3fd8bc _ZN15MenuBarInstance21UpdateAggregateUIModeE21MenuBarAnimationStylehhh + 1184 4 HIToolbox 0x000000018c490004 _ZN15MenuBarInstance19SetFullScreenUIModeEjj + 180 5 AppKit 0x000000018627fd30 -[NSApplication _setPresentationOptions:instance:flags:] + 956 6 AppKit 0x000000018611593c -[NSApplication _updateFullScreenPresentationOptionsForInstance:] + 404 7 CoreFoundation 0x0000000182d32560 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 8 CoreFoundation 0x0000000182dd0044 ___CFXRegistrationPost_block_invoke + 88 9 CoreFoundation 0x0000000182dcff8c _CFXRegistrationPost + 440 10 CoreFoundation 0x0000000182d03b64 _CFXNotificationPost + 708 11 Foundation 0x0000000183bf338c -[NSNotificationCenter postNotificationName:object:userInfo:] + 88 12 AppKit 0x00000001862802b4 spacesNotificationHandler + 96 13 SkyLight 0x000000018796d214 _ZN12_GLOBAL__N_123notify_datagram_handlerEj15CGSDatagramTypePvmS1_ + 896 14 SkyLight 0x0000000187c994d4 _ZN21CGSDatagramReadStream26dispatchMainQueueDatagramsEv + 228 15 SkyLight 0x0000000187c993d0 ___ZN21CGSDatagramReadStream15mainQueueWakeupEv_block_invoke + 28 16 libdispatch.dylib 0x0000000182ad49dc _dispatch_call_block_and_release + 32 17 libdispatch.dylib 0x0000000182ad6504 _dispatch_client_callout + 20 18 libdispatch.dylib 0x0000000182ae4d1c _dispatch_main_queue_drain + 928 19 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 22 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 23 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 24 HIToolbox 0x000000018c41bde4 ReceiveNextEventCommon + 672 25 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 26 AppKit 0x0000000185fc184c _DPSNextEvent + 632 27 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 28 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 29 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 30 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 31 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 32 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 33 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 34 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 35 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 36 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 37 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 38 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 39 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 40 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 41 Electron Framework 0x000000010acd91d8 ElectronMain + 128 42 dyld 0x0000000182933e50 start + 2544 1 HIToolbox 0x000000018c41b90c _ZN15MenuBarInstance22RemoveAutoShowObserverEv + 44 2 HIToolbox 0x000000018c490fbc _ZN15MenuBarInstance15DisableAutoShowEv + 36 3 HIToolbox 0x000000018c4910b0 _ZN15MenuBarInstanceD2Ev + 128 4 HIToolbox 0x000000018c490ee0 _ZN15MenuBarInstance7ReleaseEv + 56 5 AppKit 0x000000018661d4dc -[NSHIPresentationInstance discard] + 228 6 AppKit 0x00000001869dc8b4 -[_NSFullScreenSpace(PresentationInstance) discardPresentationInstance] + 32 7 AppKit 0x00000001869dc90c -[_NSFullScreenSpace(PresentationInstance) activateFullScreenPresentationOptions] + 64 8 AppKit 0x0000000186836968 -[_NSExitFullScreenTransitionController _doSucceededToExitFullScreen] + 40 9 AppKit 0x0000000186837440 __63-[_NSExitFullScreenTransitionController _performExitFullScreen]_block_invoke + 236 10 libxpc.dylib 0x00000001829ce42c _xpc_connection_reply_callout + 124 11 libxpc.dylib 0x00000001829ce31c _xpc_connection_call_reply_async + 88 12 libdispatch.dylib 0x0000000182ad6584 _dispatch_client_callout3 + 20 13 libdispatch.dylib 0x0000000182af4710 _dispatch_mach_msg_async_reply_invoke + 344 14 libdispatch.dylib 0x0000000182ae4c70 _dispatch_main_queue_drain + 756 15 libdispatch.dylib 0x0000000182ae496c _dispatch_main_queue_callback_4CF + 44 16 CoreFoundation 0x0000000182d7ed40 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 17 CoreFoundation 0x0000000182d3c7c0 __CFRunLoopRun + 2036 18 CoreFoundation 0x0000000182d3b878 CFRunLoopRunSpecific + 612 19 HIToolbox 0x000000018c41bfa0 RunCurrentEventLoopInMode + 292 20 HIToolbox 0x000000018c41bc30 ReceiveNextEventCommon + 236 21 HIToolbox 0x000000018c41bb2c _BlockUntilNextEventMatchingListInModeWithFilter + 72 22 AppKit 0x0000000185fc184c _DPSNextEvent + 632 23 AppKit 0x0000000185fc09dc -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 728 24 AppKit 0x0000000185fb4e0c -[NSApplication run] + 464 25 Electron Framework 0x000000010da2e958 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9089840 26 Electron Framework 0x000000010da2d050 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 9083432 27 Electron Framework 0x000000010d9e0c28 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8771072 28 Electron Framework 0x000000010d9ab0b4 _ZN4node23GetMultiIsolatePlatformEPNS_11IsolateDataE + 8551052 29 Electron Framework 0x000000010cc9ba10 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3653888 30 Electron Framework 0x000000010cc9d324 _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3660308 31 Electron Framework 0x000000010cc9969c _ZN2v88internal20SetupIsolateDelegate13SetupBuiltinsEPNS0_7IsolateEb + 3644812 32 Electron Framework 0x000000010afa5ff4 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 13524 33 Electron Framework 0x000000010afa6f00 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 17376 34 Electron Framework 0x000000010afa6d50 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 16944 35 Electron Framework 0x000000010afa5814 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 11508 36 Electron Framework 0x000000010afa5a40 _ZN2v88internal8compiler10BasicBlock15set_loop_headerEPS2_ + 12064 37 Electron Framework 0x000000010acd91d8 ElectronMain + 128 38 dyld 0x0000000182933e50 start + 2544 ```
https://github.com/electron/electron/issues/39077
https://github.com/electron/electron/pull/39086
455f57322f705fdd67751328e8f1feaf6bd29409
12548294c0b2639d34c05c544f56545004efee01
2023-07-12T20:04:56Z
c++
2023-07-25T16:18:36Z
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/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/browser.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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) 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]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // 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_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[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_ = [[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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); [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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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]; [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]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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]]; [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_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ 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::ShowAllTabs() { [window_ toggleTabOverview: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_ = [[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()) { 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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
39,078
[Bug]: Child window can't be minimized on Mac when it's brought back by activating the parent window rather than through the minimize section of the dock
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to be able to minimize a child window correctly ### Actual Behavior After the first minimize, if I get the window back by activating the parent window (since I guess the child is brought up since it's supposed to be on top of the parent), I can't minimize/close it. It needs to be retrieved from the minimize section of the doc ### Testcase Gist URL https://gist.github.com/pushkin-/c7f43c9692b085adca3a784a390eb89b ### Additional Information 1. start gist 2. click Open Window button 3. minimize the child window (seems to work the first time) 4. then pull it back from the dock (I had to click on some other application and then my app) 5. now the minimize button doesn't do anything. Neither does the X. If I bring the child window back via the minimize section of the dock, then it works fine. Only happens when the window is a child window.
https://github.com/electron/electron/issues/39078
https://github.com/electron/electron/pull/39225
12548294c0b2639d34c05c544f56545004efee01
38c3d8df2970821f582d7adc6c3ecd400ef265df
2023-07-12T20:21:47Z
c++
2023-07-26T08:10:34Z
shell/browser/ui/cocoa/electron_ns_window_delegate.h
// Copyright (c) 2018 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_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_ #define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_ #include <Quartz/Quartz.h> #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/views_nswindow_delegate.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace electron { class NativeWindowMac; } @interface ElectronNSWindowDelegate : ViewsNSWindowDelegate <NSTouchBarDelegate, QLPreviewPanelDataSource> { @private raw_ptr<electron::NativeWindowMac> shell_; bool is_zooming_; int level_; bool is_resizable_; // Only valid during a live resize. // Used to keep track of whether a resize is happening horizontally or // vertically, even if physically the user is resizing in both directions. absl::optional<bool> resizingHorizontally_; } - (id)initWithShell:(electron::NativeWindowMac*)shell; @end #endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
39,078
[Bug]: Child window can't be minimized on Mac when it's brought back by activating the parent window rather than through the minimize section of the dock
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to be able to minimize a child window correctly ### Actual Behavior After the first minimize, if I get the window back by activating the parent window (since I guess the child is brought up since it's supposed to be on top of the parent), I can't minimize/close it. It needs to be retrieved from the minimize section of the doc ### Testcase Gist URL https://gist.github.com/pushkin-/c7f43c9692b085adca3a784a390eb89b ### Additional Information 1. start gist 2. click Open Window button 3. minimize the child window (seems to work the first time) 4. then pull it back from the dock (I had to click on some other application and then my app) 5. now the minimize button doesn't do anything. Neither does the X. If I bring the child window back via the minimize section of the dock, then it works fine. Only happens when the window is a child window.
https://github.com/electron/electron/issues/39078
https://github.com/electron/electron/pull/39225
12548294c0b2639d34c05c544f56545004efee01
38c3d8df2970821f582d7adc6c3ecd400ef265df
2023-07-12T20:21:47Z
c++
2023-07-26T08:10:34Z
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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif 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(); NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double titleBarHeight = windowSize.height() - contentSize.height(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = titleBarHeight + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); // Clamp to minimum width/height while ensuring aspect ratio remains. NSSize minSize = [window minSize]; NSSize zeroSize = shell_->has_frame() ? NSMakeSize(0, titleBarHeight) : NSZeroSize; if (!NSEqualSizes(minSize, zeroSize)) { double minWidthForAspectRatio = (minSize.height - titleBarHeight) * aspectRatio; bool atMinHeight = minSize.height > zeroSize.height && newSize.height <= minSize.height; newSize.width = atMinHeight ? minWidthForAspectRatio : std::max(newSize.width, minSize.width); double minHeightForAspectRatio = minSize.width / aspectRatio; bool atMinWidth = minSize.width > zeroSize.width && newSize.width <= minSize.width; newSize.height = atMinWidth ? minHeightForAspectRatio : std::max(newSize.height, minSize.height); } // Clamp to maximum width/height while ensuring aspect ratio remains. NSSize maxSize = [window maxSize]; if (!NSEqualSizes(maxSize, NSMakeSize(FLT_MAX, FLT_MAX))) { double maxWidthForAspectRatio = maxSize.height * aspectRatio; bool atMaxHeight = maxSize.height < FLT_MAX && newSize.height >= maxSize.height; newSize.width = atMaxHeight ? maxWidthForAspectRatio : std::min(newSize.width, maxSize.width); double maxHeightForAspectRatio = maxSize.width / aspectRatio; bool atMaxWidth = maxSize.width < FLT_MAX && newSize.width >= maxSize.width; newSize.height = atMaxWidth ? maxHeightForAspectRatio : std::min(newSize.height, maxSize.height); } } if (!resizingHorizontally_) { 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(); shell_->DetachChildren(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->AttachChildren(); 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::kEntering); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kExiting); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); 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(^{ [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
39,078
[Bug]: Child window can't be minimized on Mac when it's brought back by activating the parent window rather than through the minimize section of the dock
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to be able to minimize a child window correctly ### Actual Behavior After the first minimize, if I get the window back by activating the parent window (since I guess the child is brought up since it's supposed to be on top of the parent), I can't minimize/close it. It needs to be retrieved from the minimize section of the doc ### Testcase Gist URL https://gist.github.com/pushkin-/c7f43c9692b085adca3a784a390eb89b ### Additional Information 1. start gist 2. click Open Window button 3. minimize the child window (seems to work the first time) 4. then pull it back from the dock (I had to click on some other application and then my app) 5. now the minimize button doesn't do anything. Neither does the X. If I bring the child window back via the minimize section of the dock, then it works fine. Only happens when the window is a child window.
https://github.com/electron/electron/issues/39078
https://github.com/electron/electron/pull/39225
12548294c0b2639d34c05c544f56545004efee01
38c3d8df2970821f582d7adc6c3ecd400ef265df
2023-07-12T20:21:47Z
c++
2023-07-26T08:10:34Z
shell/browser/ui/cocoa/electron_ns_window_delegate.h
// Copyright (c) 2018 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_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_ #define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_ #include <Quartz/Quartz.h> #include "base/memory/raw_ptr.h" #include "components/remote_cocoa/app_shim/views_nswindow_delegate.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace electron { class NativeWindowMac; } @interface ElectronNSWindowDelegate : ViewsNSWindowDelegate <NSTouchBarDelegate, QLPreviewPanelDataSource> { @private raw_ptr<electron::NativeWindowMac> shell_; bool is_zooming_; int level_; bool is_resizable_; // Only valid during a live resize. // Used to keep track of whether a resize is happening horizontally or // vertically, even if physically the user is resizing in both directions. absl::optional<bool> resizingHorizontally_; } - (id)initWithShell:(electron::NativeWindowMac*)shell; @end #endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_NS_WINDOW_DELEGATE_H_
closed
electron/electron
https://github.com/electron/electron
39,078
[Bug]: Child window can't be minimized on Mac when it's brought back by activating the parent window rather than through the minimize section of the dock
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS Ventura 13.2.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior I expect to be able to minimize a child window correctly ### Actual Behavior After the first minimize, if I get the window back by activating the parent window (since I guess the child is brought up since it's supposed to be on top of the parent), I can't minimize/close it. It needs to be retrieved from the minimize section of the doc ### Testcase Gist URL https://gist.github.com/pushkin-/c7f43c9692b085adca3a784a390eb89b ### Additional Information 1. start gist 2. click Open Window button 3. minimize the child window (seems to work the first time) 4. then pull it back from the dock (I had to click on some other application and then my app) 5. now the minimize button doesn't do anything. Neither does the X. If I bring the child window back via the minimize section of the dock, then it works fine. Only happens when the window is a child window.
https://github.com/electron/electron/issues/39078
https://github.com/electron/electron/pull/39225
12548294c0b2639d34c05c544f56545004efee01
38c3d8df2970821f582d7adc6c3ecd400ef265df
2023-07-12T20:21:47Z
c++
2023-07-26T08:10:34Z
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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif 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(); NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); if (aspectRatio > 0.0) { gfx::Size windowSize = shell_->GetSize(); gfx::Size contentSize = shell_->GetContentSize(); gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); double titleBarHeight = windowSize.height() - contentSize.height(); double extraWidthPlusFrame = windowSize.width() - contentSize.width() + extraSize.width(); double extraHeightPlusFrame = titleBarHeight + extraSize.height(); newSize.width = roundf((frameSize.height - extraHeightPlusFrame) * aspectRatio + extraWidthPlusFrame); newSize.height = roundf((newSize.width - extraWidthPlusFrame) / aspectRatio + extraHeightPlusFrame); // Clamp to minimum width/height while ensuring aspect ratio remains. NSSize minSize = [window minSize]; NSSize zeroSize = shell_->has_frame() ? NSMakeSize(0, titleBarHeight) : NSZeroSize; if (!NSEqualSizes(minSize, zeroSize)) { double minWidthForAspectRatio = (minSize.height - titleBarHeight) * aspectRatio; bool atMinHeight = minSize.height > zeroSize.height && newSize.height <= minSize.height; newSize.width = atMinHeight ? minWidthForAspectRatio : std::max(newSize.width, minSize.width); double minHeightForAspectRatio = minSize.width / aspectRatio; bool atMinWidth = minSize.width > zeroSize.width && newSize.width <= minSize.width; newSize.height = atMinWidth ? minHeightForAspectRatio : std::max(newSize.height, minSize.height); } // Clamp to maximum width/height while ensuring aspect ratio remains. NSSize maxSize = [window maxSize]; if (!NSEqualSizes(maxSize, NSMakeSize(FLT_MAX, FLT_MAX))) { double maxWidthForAspectRatio = maxSize.height * aspectRatio; bool atMaxHeight = maxSize.height < FLT_MAX && newSize.height >= maxSize.height; newSize.width = atMaxHeight ? maxWidthForAspectRatio : std::min(newSize.width, maxSize.width); double maxHeightForAspectRatio = maxSize.width / aspectRatio; bool atMaxWidth = maxSize.width < FLT_MAX && newSize.width >= maxSize.width; newSize.height = atMaxWidth ? maxHeightForAspectRatio : std::min(newSize.height, maxSize.height); } } if (!resizingHorizontally_) { 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(); shell_->DetachChildren(); } - (void)windowDidMiniaturize:(NSNotification*)notification { [super windowDidMiniaturize:notification]; shell_->NotifyWindowMinimize(); } - (void)windowDidDeminiaturize:(NSNotification*)notification { [super windowDidDeminiaturize:notification]; shell_->AttachChildren(); 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::kEntering); shell_->NotifyWindowWillEnterFullScreen(); // Set resizable to true before entering fullscreen. shell_->SetResizable(true); } - (void)windowDidEnterFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); shell_->NotifyWindowEnterFullScreen(); if (shell_->HandleDeferredClose()) return; shell_->HandlePendingFullscreenTransitions(); } - (void)windowWillExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kExiting); shell_->NotifyWindowWillLeaveFullScreen(); } - (void)windowDidExitFullScreen:(NSNotification*)notification { shell_->set_fullscreen_transition_state(FullScreenTransitionState::kNone); 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(^{ [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
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
patches/webrtc/.patches
fix_fallback_to_x11_capturer_on_wayland.patch
closed
electron/electron
https://github.com/electron/electron
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
patches/webrtc/fix_mark_pipewire_capturer_as_failed_after_session_is_closed.patch
closed
electron/electron
https://github.com/electron/electron
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; DesktopCapturer::DesktopListListener::DesktopListListener( OnceCallback update_callback, OnceCallback failure_callback, bool skip_thumbnails) : update_callback_(std::move(update_callback)), failure_callback_(std::move(failure_callback)), have_thumbnail_(skip_thumbnails) {} DesktopCapturer::DesktopListListener::~DesktopListListener() = default; void DesktopCapturer::DesktopListListener::OnDelegatedSourceListSelection() { if (have_thumbnail_) { std::move(update_callback_).Run(); } else { have_selection_ = true; } } void DesktopCapturer::DesktopListListener::OnSourceThumbnailChanged(int index) { if (have_selection_) { // This is called every time a thumbnail is refreshed. Reset variable to // ensure that the callback is not run again. have_selection_ = false; // PipeWire returns a single source, so index is not relevant. std::move(update_callback_).Run(); } else { have_thumbnail_ = true; } } void DesktopCapturer::DesktopListListener::OnDelegatedSourceListDismissed() { std::move(failure_callback_).Run(); } void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); if (capture_window && capture_screen) { // Some capturers like PipeWire suppport a single capturer for both screens // and windows. Use it if possible, treating both as window capture if (auto capturer = webrtc::DesktopCapturer::CreateGenericCapturer( content::desktop_capture::CreateDesktopCaptureOptions()); capturer && capturer->GetDelegatedSourceListController()) { capture_screen_ = false; capture_window_ = capture_window; window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); return; } } // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); if (window_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); } else { window_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()); if (screen_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); screen_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); screen_capturer_->StartUpdating(screen_listener_.get()); } else { screen_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { HandleFailure(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } void DesktopCapturer::HandleFailure() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
patches/webrtc/.patches
fix_fallback_to_x11_capturer_on_wayland.patch
closed
electron/electron
https://github.com/electron/electron
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
patches/webrtc/fix_mark_pipewire_capturer_as_failed_after_session_is_closed.patch
closed
electron/electron
https://github.com/electron/electron
39,112
[Bug]: desktopCapturer fails to generate thumbnails after a PipeWire stream is cancelled externally
### 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 25.3.0 ### What operating system are you using? Other Linux ### Operating System Version Fedora 38 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Get screencast sources using `desktopCapturer.getSources()` on Wayland 2. Select a source on the permission popup 3. Start a screencast stream using `navigator.mediaDevices.getUserMedia()` 4. Interrupt the stream by cancelling screen sharing using OS controls, like on the top bar of GNOME shell 5. Try to fetch screencast sources again using `desktopCapturer.getSources()`, with thumbnails 6. Select a source on the permission popup 7. Sources and thumbnails should be returned by `desktopCapturer.getSources()` ### Actual Behavior The second call to `desktopCapturer.getSources()` does not complete. ### Testcase Gist URL https://gist.github.com/aiddya/d368bc2cb7f72a9b030b918ee1332299 ### Additional Information Filing this as a known issue. This issue is not reproducible with Chromium, so it's related to how `DesktopCapturer` and `NativeDesktopMediaList` objects are handled in Electron.
https://github.com/electron/electron/issues/39112
https://github.com/electron/electron/pull/39194
38c3d8df2970821f582d7adc6c3ecd400ef265df
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
2023-07-15T17:46:11Z
c++
2023-07-26T08:40:19Z
shell/browser/api/electron_api_desktop_capturer.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_desktop_capturer.h" #include <map> #include <memory> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/media/webrtc/desktop_media_list.h" #include "chrome/browser/media/webrtc/window_icon_util.h" #include "content/public/browser/desktop_capture.h" #include "gin/object_template_builder.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_includes.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #if defined(USE_OZONE) #include "ui/ozone/buildflags.h" #if BUILDFLAG(OZONE_PLATFORM_X11) #define USE_OZONE_PLATFORM_X11 #endif #endif #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) #include "base/logging.h" #include "ui/base/x/x11_display_util.h" #include "ui/base/x/x11_util.h" #include "ui/display/util/edid_parser.h" // nogncheck #include "ui/gfx/x/randr.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto_util.h" #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_LINUX) // Private function in ui/base/x/x11_display_util.cc std::map<x11::RandR::Output, int> GetMonitors(int version, x11::RandR* randr, x11::Window window) { std::map<x11::RandR::Output, int> output_to_monitor; if (version >= 105) { if (auto reply = randr->GetMonitors({window}).Sync()) { for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { for (x11::RandR::Output output : reply->monitors[monitor].outputs) output_to_monitor[output] = monitor; } } } return output_to_monitor; } // Get the EDID data from the |output| and stores to |edid|. // Private function in ui/base/x/x11_display_util.cc std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, x11::RandR::Output output) { constexpr const char kRandrEdidProperty[] = "EDID"; auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ .output = output, .property = x11::GetAtom(kRandrEdidProperty), .long_length = 128}); auto response = future.Sync(); std::vector<uint8_t> edid; if (response && response->format == 8 && response->type != x11::Atom::None) edid = std::move(response->data); return edid; } // Find the mapping from monitor name atom to the display identifier // that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo // in ui/base/x/x11_display_util.cc std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { auto* connection = x11::Connection::Get(); auto& randr = connection->randr(); auto x_root_window = ui::GetX11RootWindow(); int version = ui::GetXrandrVersion(); std::map<int32_t, uint32_t> monitor_atom_to_display; auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); if (!resources) { LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; return monitor_atom_to_display; } std::map<x11::RandR::Output, int> output_to_monitor = GetMonitors(version, &randr, x_root_window); auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); for (size_t i = 0; i < resources->outputs.size(); i++) { x11::RandR::Output output_id = resources->outputs[i]; auto output_info = randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); if (!output_info) continue; if (output_info->connection != x11::RandR::RandRConnection::Connected) continue; if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) continue; auto crtc = randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) .Sync(); if (!crtc) continue; display::EdidParser edid_parser( GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); auto output_32 = static_cast<uint32_t>(output_id); int64_t display_id = output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); // It isn't ideal, but if we can't parse the EDID data, fall back on the // display number. if (!display_id) display_id = i; // Find the mapping between output identifier and the monitor name atom // Note this isn't the atom string, but the numeric atom identifier, // since this is what the WebRTC system uses as the display identifier auto output_monitor_iter = output_to_monitor.find(output_id); if (output_monitor_iter != output_to_monitor.end()) { x11::Atom atom = monitors_reply->monitors[output_monitor_iter->second].name; monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; } } return monitor_atom_to_display; } #endif namespace gin { template <> struct Converter<electron::api::DesktopCapturer::Source> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const electron::api::DesktopCapturer::Source& source) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); content::DesktopMediaID id = source.media_list_source.id; dict.Set("name", base::UTF16ToUTF8(source.media_list_source.name)); dict.Set("id", id.ToString()); dict.Set("thumbnail", electron::api::NativeImage::Create( isolate, gfx::Image(source.media_list_source.thumbnail))); dict.Set("display_id", source.display_id); if (source.fetch_icon) { dict.Set( "appIcon", electron::api::NativeImage::Create( isolate, gfx::Image(GetWindowIcon(source.media_list_source.id)))); } else { dict.Set("appIcon", nullptr); } return ConvertToV8(isolate, dict); } }; } // namespace gin namespace electron::api { gin::WrapperInfo DesktopCapturer::kWrapperInfo = {gin::kEmbedderNativeGin}; DesktopCapturer::DesktopCapturer(v8::Isolate* isolate) {} DesktopCapturer::~DesktopCapturer() = default; DesktopCapturer::DesktopListListener::DesktopListListener( OnceCallback update_callback, OnceCallback failure_callback, bool skip_thumbnails) : update_callback_(std::move(update_callback)), failure_callback_(std::move(failure_callback)), have_thumbnail_(skip_thumbnails) {} DesktopCapturer::DesktopListListener::~DesktopListListener() = default; void DesktopCapturer::DesktopListListener::OnDelegatedSourceListSelection() { if (have_thumbnail_) { std::move(update_callback_).Run(); } else { have_selection_ = true; } } void DesktopCapturer::DesktopListListener::OnSourceThumbnailChanged(int index) { if (have_selection_) { // This is called every time a thumbnail is refreshed. Reset variable to // ensure that the callback is not run again. have_selection_ = false; // PipeWire returns a single source, so index is not relevant. std::move(update_callback_).Run(); } else { have_thumbnail_ = true; } } void DesktopCapturer::DesktopListListener::OnDelegatedSourceListDismissed() { std::move(failure_callback_).Run(); } void DesktopCapturer::StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, bool fetch_window_icons) { fetch_window_icons_ = fetch_window_icons; #if BUILDFLAG(IS_WIN) if (content::desktop_capture::CreateDesktopCaptureOptions() .allow_directx_capturer()) { // DxgiDuplicatorController should be alive in this scope according to // screen_capturer_win.cc. auto duplicator = webrtc::DxgiDuplicatorController::Instance(); using_directx_capturer_ = webrtc::ScreenCapturerWinDirectx::IsSupported(); } #endif // BUILDFLAG(IS_WIN) // clear any existing captured sources. captured_sources_.clear(); if (capture_window && capture_screen) { // Some capturers like PipeWire suppport a single capturer for both screens // and windows. Use it if possible, treating both as window capture if (auto capturer = webrtc::DesktopCapturer::CreateGenericCapturer( content::desktop_capture::CreateDesktopCaptureOptions()); capturer && capturer->GetDelegatedSourceListController()) { capture_screen_ = false; capture_window_ = capture_window; window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); return; } } // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen; { // Initialize the source list. // Apply the new thumbnail size and restart capture. if (capture_window) { if (auto capturer = content::desktop_capture::CreateWindowCapturer(); capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, std::move(capturer)); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), window_capturer_.get()); if (window_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); window_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); window_capturer_->StartUpdating(window_listener_.get()); } else { window_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } if (capture_screen) { if (auto capturer = content::desktop_capture::CreateScreenCapturer(); capturer) { screen_capturer_ = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, std::move(capturer)); screen_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), screen_capturer_.get()); if (screen_capturer_->IsSourceListDelegated()) { OnceCallback failure_callback = base::BindOnce( &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); screen_listener_ = std::make_unique<DesktopListListener>( std::move(update_callback), std::move(failure_callback), thumbnail_size.IsEmpty()); screen_capturer_->StartUpdating(screen_listener_.get()); } else { screen_capturer_->Update(std::move(update_callback), /* refresh_thumbnails = */ true); } } } } } void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { if (capture_window_ && list->GetMediaListType() == DesktopMediaList::Type::kWindow) { capture_window_ = false; std::vector<DesktopCapturer::Source> window_sources; window_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { window_sources.emplace_back(list->GetSource(i), std::string(), fetch_window_icons_); } std::move(window_sources.begin(), window_sources.end(), std::back_inserter(captured_sources_)); } if (capture_screen_ && list->GetMediaListType() == DesktopMediaList::Type::kScreen) { capture_screen_ = false; std::vector<DesktopCapturer::Source> screen_sources; screen_sources.reserve(list->GetSourceCount()); for (int i = 0; i < list->GetSourceCount(); i++) { screen_sources.emplace_back(list->GetSource(i), std::string()); } #if BUILDFLAG(IS_WIN) // Gather the same unique screen IDs used by the electron.screen API in // order to provide an association between it and // desktopCapturer/getUserMedia. This is only required when using the // DirectX capturer, otherwise the IDs across the APIs already match. if (using_directx_capturer_) { std::vector<std::string> device_names; // Crucially, this list of device names will be in the same order as // |media_list_sources|. if (!webrtc::DxgiDuplicatorController::Instance()->GetDeviceNames( &device_names)) { HandleFailure(); return; } int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; std::wstring wide_device_name; base::UTF8ToWide(device_name.c_str(), device_name.size(), &wide_device_name); const int64_t device_id = display::win::internal::DisplayInfo::DeviceIdFromDeviceName( wide_device_name.c_str()); source.display_id = base::NumberToString(device_id); } } #elif BUILDFLAG(IS_MAC) // On Mac, the IDs across the APIs match. for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) // On Linux, with X11, the source id is the numeric value of the // display name atom and the display id is either the EDID or the // loop index when that display was found (see // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) std::map<int32_t, uint32_t> monitor_atom_to_display_id = MonitorAtomIdToDisplayId(); for (auto& source : screen_sources) { auto display_id_iter = monitor_atom_to_display_id.find(source.media_list_source.id.id); if (display_id_iter != monitor_atom_to_display_id.end()) source.display_id = base::NumberToString(display_id_iter->second); } #endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); } if (!capture_window_ && !capture_screen_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onfinished", captured_sources_); Unpin(); } } void DesktopCapturer::HandleFailure() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); gin_helper::CallMethod(this, "_onerror", "Failed to get sources."); Unpin(); } // static gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { auto handle = gin::CreateHandle(isolate, new DesktopCapturer(isolate)); // Keep reference alive until capturing has finished. handle->Pin(isolate); return handle; } gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) .SetMethod("startHandling", &DesktopCapturer::StartHandling); } const char* DesktopCapturer::GetTypeName() { return "DesktopCapturer"; } } // namespace electron::api namespace { void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); } } // namespace NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_desktop_capturer, Initialize)
closed
electron/electron
https://github.com/electron/electron
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; virtual void RemoveChildWindow(NativeWindow* child) = 0; virtual void AttachChildren() = 0; virtual void DetachChildren() = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void ShowAllTabs(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } void add_child_window(NativeWindow* child) { child_windows_.push_back(child); } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; // Minimum and maximum size. absl::optional<extensions::SizeConstraints> size_constraints_; // Same as above but stored as content size, we are storing 2 types of size // constraints beacause converting between them will cause rounding errors // on HiDPI displays on some environments. absl::optional<extensions::SizeConstraints> content_size_constraints_; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; std::list<NativeWindow*> child_windows_; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "electron/shell/common/api/api.mojom.h" #include "shell/browser/native_window.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void ShowAllTabs() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; // Remove the specified child window without closing it. void RemoveChildWindow(NativeWindow* child) override; void RemoveChildFromParentWindow(NativeWindow* child); // Attach child windows, if the window is visible. void AttachChildren() override; // Detach window from parent without destroying it. void DetachChildren() override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_; } ElectronTouchBar* touch_bar() const { return touch_bar_; } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. ElectronNSWindowDelegate* __strong window_delegate_; ElectronPreviewItem* __strong preview_item_; ElectronTouchBar* __strong touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. WindowButtonsProxy* __strong buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
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/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/browser.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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) 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]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // 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_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[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_ = [[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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); [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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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]; [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]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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]]; [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_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ 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::ShowAllTabs() { [window_ toggleTabOverview: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_ = [[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()) { 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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, 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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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. 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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); 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; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); 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-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } 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.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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); }); }); describe('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('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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') as Promise<[any, boolean]>; 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('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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') as [any, WebContents]; 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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('node: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') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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') as [any, BrowserWindow]; // 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') as Promise<[any, WebContents]>, 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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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') as Promise<[any, WebContents]>; 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') as Promise<[any, WebContents]>, 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('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); 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'); } }); // DISABLED-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('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('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); 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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('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(1000); 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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // 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') as Promise<[any, BrowserWindow]>; 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'); }); }); describe('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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); 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
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
shell/browser/native_window.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_ #include <list> #include <memory> #include <queue> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/web_contents_user_data.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/app_window/size_constraints.h" #include "shell/browser/draggable_region_provider.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/views/widget/widget_delegate.h" class SkRegion; namespace content { struct NativeWebKeyboardEvent; } namespace gfx { class Image; class Point; class Rect; enum class ResizeEdge; class Size; } // namespace gfx namespace gin_helper { class Dictionary; class PersistentDictionary; } // namespace gin_helper namespace electron { class ElectronMenuModel; class NativeBrowserView; namespace api { class BrowserView; } #if BUILDFLAG(IS_MAC) typedef NSView* NativeWindowHandle; #else typedef gfx::AcceleratedWidget NativeWindowHandle; #endif class NativeWindow : public base::SupportsUserData, public views::WidgetDelegate { public: ~NativeWindow() override; // disable copy NativeWindow(const NativeWindow&) = delete; NativeWindow& operator=(const NativeWindow&) = delete; // Create window with existing WebContents, the caller is responsible for // managing the window's live. static NativeWindow* Create(const gin_helper::Dictionary& options, NativeWindow* parent = nullptr); void InitFromOptions(const gin_helper::Dictionary& options); virtual void SetContentView(views::View* view) = 0; virtual void Close() = 0; virtual void CloseImmediately() = 0; virtual bool IsClosed() const; virtual void Focus(bool focus) = 0; virtual bool IsFocused() = 0; virtual void Show() = 0; virtual void ShowInactive() = 0; virtual void Hide() = 0; virtual bool IsVisible() = 0; virtual bool IsEnabled() = 0; virtual void SetEnabled(bool enable) = 0; virtual void Maximize() = 0; virtual void Unmaximize() = 0; virtual bool IsMaximized() = 0; virtual void Minimize() = 0; virtual void Restore() = 0; virtual bool IsMinimized() = 0; virtual void SetFullScreen(bool fullscreen) = 0; virtual bool IsFullscreen() const = 0; virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0; virtual gfx::Rect GetBounds() = 0; virtual void SetSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetSize(); virtual void SetPosition(const gfx::Point& position, bool animate = false); virtual gfx::Point GetPosition(); virtual void SetContentSize(const gfx::Size& size, bool animate = false); virtual gfx::Size GetContentSize(); virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false); virtual gfx::Rect GetContentBounds(); virtual bool IsNormal(); virtual gfx::Rect GetNormalBounds() = 0; virtual void SetSizeConstraints( const extensions::SizeConstraints& window_constraints); virtual extensions::SizeConstraints GetSizeConstraints() const; virtual void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints); virtual extensions::SizeConstraints GetContentSizeConstraints() const; virtual void SetMinimumSize(const gfx::Size& size); virtual gfx::Size GetMinimumSize() const; virtual void SetMaximumSize(const gfx::Size& size); virtual gfx::Size GetMaximumSize() const; virtual gfx::Size GetContentMinimumSize() const; virtual gfx::Size GetContentMaximumSize() const; virtual void SetSheetOffset(const double offsetX, const double offsetY); virtual double GetSheetOffsetX(); virtual double GetSheetOffsetY(); virtual void SetResizable(bool resizable) = 0; virtual bool MoveAbove(const std::string& sourceId) = 0; virtual void MoveTop() = 0; virtual bool IsResizable() = 0; virtual void SetMovable(bool movable) = 0; virtual bool IsMovable() = 0; virtual void SetMinimizable(bool minimizable) = 0; virtual bool IsMinimizable() = 0; virtual void SetMaximizable(bool maximizable) = 0; virtual bool IsMaximizable() = 0; virtual void SetFullScreenable(bool fullscreenable) = 0; virtual bool IsFullScreenable() = 0; virtual void SetClosable(bool closable) = 0; virtual bool IsClosable() = 0; virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level = "floating", int relativeLevel = 0) = 0; virtual ui::ZOrderLevel GetZOrderLevel() = 0; virtual void Center() = 0; virtual void Invalidate() = 0; virtual void SetTitle(const std::string& title) = 0; virtual std::string GetTitle() = 0; #if BUILDFLAG(IS_MAC) virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; virtual void RemoveChildWindow(NativeWindow* child) = 0; virtual void AttachChildren() = 0; virtual void DetachChildren() = 0; #endif // Ability to augment the window title for the screen readers. void SetAccessibleTitle(const std::string& title); std::string GetAccessibleTitle(); virtual void FlashFrame(bool flash) = 0; virtual void SetSkipTaskbar(bool skip) = 0; virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0; virtual bool IsExcludedFromShownWindowsMenu() = 0; virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0; virtual bool IsSimpleFullScreen() = 0; virtual void SetKiosk(bool kiosk) = 0; virtual bool IsKiosk() = 0; virtual bool IsTabletMode() const; virtual void SetBackgroundColor(SkColor color) = 0; virtual SkColor GetBackgroundColor() = 0; virtual void InvalidateShadow(); virtual void SetHasShadow(bool has_shadow) = 0; virtual bool HasShadow() = 0; virtual void SetOpacity(const double opacity) = 0; virtual double GetOpacity() = 0; virtual void SetRepresentedFilename(const std::string& filename); virtual std::string GetRepresentedFilename(); virtual void SetDocumentEdited(bool edited); virtual bool IsDocumentEdited(); virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0; virtual void SetContentProtection(bool enable) = 0; virtual void SetFocusable(bool focusable); virtual bool IsFocusable(); virtual void SetMenu(ElectronMenuModel* menu); virtual void SetParentWindow(NativeWindow* parent); virtual void AddBrowserView(NativeBrowserView* browser_view) = 0; virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0; virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0; virtual content::DesktopMediaID GetDesktopMediaID() const = 0; virtual gfx::NativeView GetNativeView() const = 0; virtual gfx::NativeWindow GetNativeWindow() const = 0; virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0; virtual NativeWindowHandle GetNativeWindowHandle() const = 0; // Taskbar/Dock APIs. enum class ProgressState { kNone, // no progress, no marking kIndeterminate, // progress, indeterminate kError, // progress, errored (red) kPaused, // progress, paused (yellow) kNormal, // progress, not marked (green) }; virtual void SetProgressBar(double progress, const ProgressState state) = 0; virtual void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) = 0; // Workspace APIs. virtual void SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen = false, bool skipTransformProcessType = false) = 0; virtual bool IsVisibleOnAllWorkspaces() = 0; virtual void SetAutoHideCursor(bool auto_hide); // Vibrancy API virtual void SetVibrancy(const std::string& type); virtual void SetBackgroundMaterial(const std::string& type); // Traffic Light API #if BUILDFLAG(IS_MAC) virtual void SetWindowButtonVisibility(bool visible) = 0; virtual bool GetWindowButtonVisibility() const = 0; virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0; virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0; virtual void RedrawTrafficLights() = 0; virtual void UpdateFrame() = 0; #endif // whether windows should be ignored by mission control #if BUILDFLAG(IS_MAC) virtual bool IsHiddenInMissionControl() = 0; virtual void SetHiddenInMissionControl(bool hidden) = 0; #endif // Touchbar API virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items); virtual void RefreshTouchBarItem(const std::string& item_id); virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item); // Native Tab API virtual void SelectPreviousTab(); virtual void SelectNextTab(); virtual void ShowAllTabs(); virtual void MergeAllWindows(); virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); virtual bool IsMenuBarAutoHide(); virtual void SetMenuBarVisibility(bool visible); virtual bool IsMenuBarVisible(); // Set the aspect ratio when resizing window. double GetAspectRatio(); gfx::Size GetAspectRatioExtraSize(); virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. virtual void PreviewFile(const std::string& path, const std::string& display_name); virtual void CloseFilePreview(); virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {} // Converts between content bounds and window bounds. virtual gfx::Rect ContentBoundsToWindowBounds( const gfx::Rect& bounds) const = 0; virtual gfx::Rect WindowBoundsToContentBounds( const gfx::Rect& bounds) const = 0; base::WeakPtr<NativeWindow> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } virtual gfx::Rect GetWindowControlsOverlayRect(); virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect); // Methods called by the WebContents. virtual void HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) {} // Public API used by platform-dependent delegates and observers to send UI // related notifications. void NotifyWindowRequestPreferredWidth(int* width); void NotifyWindowCloseButtonClicked(); void NotifyWindowClosed(); void NotifyWindowEndSession(); void NotifyWindowBlur(); void NotifyWindowFocus(); void NotifyWindowShow(); void NotifyWindowIsKeyChanged(bool is_key); void NotifyWindowHide(); void NotifyWindowMaximize(); void NotifyWindowUnmaximize(); void NotifyWindowMinimize(); void NotifyWindowRestore(); void NotifyWindowMove(); void NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default); void NotifyWindowResize(); void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); void NotifyWindowSheetEnd(); virtual void NotifyWindowEnterFullScreen(); virtual void NotifyWindowLeaveFullScreen(); void NotifyWindowEnterHtmlFullScreen(); void NotifyWindowLeaveHtmlFullScreen(); void NotifyWindowAlwaysOnTopChanged(); void NotifyWindowExecuteAppCommand(const std::string& command); void NotifyTouchBarItemInteraction(const std::string& item_id, base::Value::Dict details); void NotifyNewWindowForTab(); void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default); void NotifyLayoutWindowControlsOverlay(); #if BUILDFLAG(IS_WIN) void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param); #endif void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); } void RemoveObserver(NativeWindowObserver* obs) { observers_.RemoveObserver(obs); } // Handle fullscreen transitions. void HandlePendingFullscreenTransitions(); enum class FullScreenTransitionState { kEntering, kExiting, kNone }; void set_fullscreen_transition_state(FullScreenTransitionState state) { fullscreen_transition_state_ = state; } FullScreenTransitionState fullscreen_transition_state() const { return fullscreen_transition_state_; } enum class FullScreenTransitionType { kHTML, kNative, kNone }; void set_fullscreen_transition_type(FullScreenTransitionType type) { fullscreen_transition_type_ = type; } FullScreenTransitionType fullscreen_transition_type() const { return fullscreen_transition_type_; } views::Widget* widget() const { return widget_.get(); } views::View* content_view() const { return content_view_; } enum class TitleBarStyle { kNormal, kHidden, kHiddenInset, kCustomButtonsOnHover, }; TitleBarStyle title_bar_style() const { return title_bar_style_; } int titlebar_overlay_height() const { return titlebar_overlay_height_; } void set_titlebar_overlay_height(int height) { titlebar_overlay_height_ = height; } bool titlebar_overlay_enabled() const { return titlebar_overlay_; } bool has_frame() const { return has_frame_; } void set_has_frame(bool has_frame) { has_frame_ = has_frame; } bool has_client_frame() const { return has_client_frame_; } bool transparent() const { return transparent_; } bool enable_larger_than_screen() const { return enable_larger_than_screen_; } NativeWindow* parent() const { return parent_; } bool is_modal() const { return is_modal_; } std::list<NativeBrowserView*> browser_views() const { return browser_views_; } int32_t window_id() const { return next_id_; } void add_child_window(NativeWindow* child) { child_windows_.push_back(child); } int NonClientHitTest(const gfx::Point& point); void AddDraggableRegionProvider(DraggableRegionProvider* provider); void RemoveDraggableRegionProvider(DraggableRegionProvider* provider); protected: friend class api::BrowserView; NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent); // views::WidgetDelegate: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; std::u16string GetAccessibleWindowTitle() const override; void set_content_view(views::View* view) { content_view_ = view; } void add_browser_view(NativeBrowserView* browser_view) { browser_views_.push_back(browser_view); } void remove_browser_view(NativeBrowserView* browser_view) { browser_views_.remove_if( [&browser_view](NativeBrowserView* n) { return (n == browser_view); }); } // The boolean parsing of the "titleBarOverlay" option bool titlebar_overlay_ = false; // The custom height parsed from the "height" option in a Object // "titleBarOverlay" int titlebar_overlay_height_ = 0; // The "titleBarStyle" option. TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal; // Minimum and maximum size. absl::optional<extensions::SizeConstraints> size_constraints_; // Same as above but stored as content size, we are storing 2 types of size // constraints beacause converting between them will cause rounding errors // on HiDPI displays on some environments. absl::optional<extensions::SizeConstraints> content_size_constraints_; std::queue<bool> pending_transitions_; FullScreenTransitionState fullscreen_transition_state_ = FullScreenTransitionState::kNone; FullScreenTransitionType fullscreen_transition_type_ = FullScreenTransitionType::kNone; std::list<NativeWindow*> child_windows_; private: std::unique_ptr<views::Widget> widget_; static int32_t next_id_; // The content view, weak ref. raw_ptr<views::View> content_view_ = nullptr; // Whether window has standard frame. bool has_frame_ = true; // Whether window has standard frame, but it's drawn by Electron (the client // application) instead of the OS. Currently only has meaning on Linux for // Wayland hosts. bool has_client_frame_ = false; // Whether window is transparent. bool transparent_ = false; // Whether window can be resized larger than screen. bool enable_larger_than_screen_ = false; // The windows has been closed. bool is_closed_ = false; // Used to display sheets at the appropriate horizontal and vertical offsets // on macOS. double sheet_offset_x_ = 0.0; double sheet_offset_y_ = 0.0; // Used to maintain the aspect ratio of a view which is inside of the // content view. double aspect_ratio_ = 0.0; gfx::Size aspect_ratio_extraSize_; // The parent window, it is guaranteed to be valid during this window's life. raw_ptr<NativeWindow> parent_ = nullptr; // Is this a modal window. bool is_modal_ = false; // The browser view layer. std::list<NativeBrowserView*> browser_views_; std::list<DraggableRegionProvider*> draggable_region_providers_; // Observers of this window. base::ObserverList<NativeWindowObserver> observers_; // Accessible title. std::u16string accessible_title_; gfx::Rect overlay_rect_; base::WeakPtrFactory<NativeWindow> weak_factory_{this}; }; // This class provides a hook to get a NativeWindow from a WebContents. class NativeWindowRelay : public content::WebContentsUserData<NativeWindowRelay> { public: static void CreateForWebContents(content::WebContents*, base::WeakPtr<NativeWindow>); ~NativeWindowRelay() override; NativeWindow* GetNativeWindow() const { return native_window_.get(); } WEB_CONTENTS_USER_DATA_KEY_DECL(); private: friend class content::WebContentsUserData<NativeWindow>; explicit NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window); base::WeakPtr<NativeWindow> native_window_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
closed
electron/electron
https://github.com/electron/electron
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
shell/browser/native_window_mac.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_ #import <Cocoa/Cocoa.h> #include <memory> #include <string> #include <vector> #include "electron/shell/common/api/api.mojom.h" #include "shell/browser/native_window.h" #include "ui/display/display_observer.h" #include "ui/native_theme/native_theme_observer.h" #include "ui/views/controls/native/native_view_host.h" @class ElectronNSWindow; @class ElectronNSWindowDelegate; @class ElectronPreviewItem; @class ElectronTouchBar; @class WindowButtonsProxy; namespace electron { class RootViewMac; class NativeWindowMac : public NativeWindow, public ui::NativeThemeObserver, public display::DisplayObserver { public: NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent); ~NativeWindowMac() override; // NativeWindow: void SetContentView(views::View* view) override; void Close() override; void CloseImmediately() override; void Focus(bool focus) override; bool IsFocused() override; void Show() override; void ShowInactive() override; void Hide() override; bool IsVisible() override; bool IsEnabled() override; void SetEnabled(bool enable) override; void Maximize() override; void Unmaximize() override; bool IsMaximized() override; void Minimize() override; void Restore() override; bool IsMinimized() override; void SetFullScreen(bool fullscreen) override; bool IsFullscreen() const override; void SetBounds(const gfx::Rect& bounds, bool animate = false) override; gfx::Rect GetBounds() override; bool IsNormal() override; gfx::Rect GetNormalBounds() override; void SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) override; void SetResizable(bool resizable) override; bool MoveAbove(const std::string& sourceId) override; void MoveTop() override; bool IsResizable() override; void SetMovable(bool movable) override; bool IsMovable() override; void SetMinimizable(bool minimizable) override; bool IsMinimizable() override; void SetMaximizable(bool maximizable) override; bool IsMaximizable() override; void SetFullScreenable(bool fullscreenable) override; bool IsFullScreenable() override; void SetClosable(bool closable) override; bool IsClosable() override; void SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relative_level) override; std::string GetAlwaysOnTopLevel() override; ui::ZOrderLevel GetZOrderLevel() override; void Center() override; void Invalidate() override; void SetTitle(const std::string& title) override; std::string GetTitle() override; void FlashFrame(bool flash) override; void SetSkipTaskbar(bool skip) override; void SetExcludedFromShownWindowsMenu(bool excluded) override; bool IsExcludedFromShownWindowsMenu() override; void SetSimpleFullScreen(bool simple_fullscreen) override; bool IsSimpleFullScreen() override; void SetKiosk(bool kiosk) override; bool IsKiosk() override; void SetBackgroundColor(SkColor color) override; SkColor GetBackgroundColor() override; void InvalidateShadow() override; void SetHasShadow(bool has_shadow) override; bool HasShadow() override; void SetOpacity(const double opacity) override; double GetOpacity() override; void SetRepresentedFilename(const std::string& filename) override; std::string GetRepresentedFilename() override; void SetDocumentEdited(bool edited) override; bool IsDocumentEdited() override; void SetIgnoreMouseEvents(bool ignore, bool forward) override; bool IsHiddenInMissionControl() override; void SetHiddenInMissionControl(bool hidden) override; void SetContentProtection(bool enable) override; void SetFocusable(bool focusable) override; bool IsFocusable() override; void AddBrowserView(NativeBrowserView* browser_view) override; void RemoveBrowserView(NativeBrowserView* browser_view) override; void SetTopBrowserView(NativeBrowserView* browser_view) override; void SetParentWindow(NativeWindow* parent) override; content::DesktopMediaID GetDesktopMediaID() const override; gfx::NativeView GetNativeView() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::AcceleratedWidget GetAcceleratedWidget() const override; NativeWindowHandle GetNativeWindowHandle() const override; void SetProgressBar(double progress, const ProgressState state) override; void SetOverlayIcon(const gfx::Image& overlay, const std::string& description) override; void SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) override; bool IsVisibleOnAllWorkspaces() override; void SetAutoHideCursor(bool auto_hide) override; void SetVibrancy(const std::string& type) override; void SetWindowButtonVisibility(bool visible) override; bool GetWindowButtonVisibility() const override; void SetWindowButtonPosition(absl::optional<gfx::Point> position) override; absl::optional<gfx::Point> GetWindowButtonPosition() const override; void RedrawTrafficLights() override; void UpdateFrame() override; void SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) override; void RefreshTouchBarItem(const std::string& item_id) override; void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override; void SelectPreviousTab() override; void SelectNextTab() override; void ShowAllTabs() override; void MergeAllWindows() override; void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, const std::string& display_name) override; void CloseFilePreview() override; gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override; gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override; gfx::Rect GetWindowControlsOverlayRect() override; void NotifyWindowEnterFullScreen() override; void NotifyWindowLeaveFullScreen() override; void SetActive(bool is_key) override; bool IsActive() const override; // Remove the specified child window without closing it. void RemoveChildWindow(NativeWindow* child) override; void RemoveChildFromParentWindow(NativeWindow* child); // Attach child windows, if the window is visible. void AttachChildren() override; // Detach window from parent without destroying it. void DetachChildren() override; void NotifyWindowWillEnterFullScreen(); void NotifyWindowWillLeaveFullScreen(); // Cleanup observers when window is getting closed. Note that the destructor // can be called much later after window gets closed, so we should not do // cleanup in destructor. void Cleanup(); void UpdateVibrancyRadii(bool fullscreen); void UpdateWindowOriginalFrame(); // Set the attribute of NSWindow while work around a bug of zoom button. bool HasStyleMask(NSUInteger flag) const; void SetStyleMask(bool on, NSUInteger flag); void SetCollectionBehavior(bool on, NSUInteger flag); void SetWindowLevel(int level); bool HandleDeferredClose(); void SetHasDeferredWindowClose(bool defer_close) { has_deferred_window_close_ = defer_close; } enum class VisualEffectState { kFollowWindow, kActive, kInactive, }; ElectronPreviewItem* preview_item() const { return preview_item_; } ElectronTouchBar* touch_bar() const { return touch_bar_; } bool zoom_to_page_width() const { return zoom_to_page_width_; } bool always_simple_fullscreen() const { return always_simple_fullscreen_; } // We need to save the result of windowWillUseStandardFrame:defaultFrame // because macOS calls it with what it refers to as the "best fit" frame for a // zoom. This means that even if an aspect ratio is set, macOS might adjust it // to better fit the screen. // // Thus, we can't just calculate the maximized aspect ratio'd sizing from // the current visible screen and compare that to the current window's frame // to determine whether a window is maximized. NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; } void set_default_frame_for_zoom(NSRect frame) { default_frame_for_zoom_ = frame; } protected: // views::WidgetDelegate: views::View* GetContentsView() override; bool CanMaximize() const override; std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView( views::Widget* widget) override; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; // display::DisplayObserver: void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; private: // Add custom layers to the content view. void AddContentViewLayers(); void InternalSetWindowButtonVisibility(bool visible); void InternalSetParentWindow(NativeWindow* parent, bool attach); void SetForwardMouseMessages(bool forward); ElectronNSWindow* window_; // Weak ref, managed by widget_. ElectronNSWindowDelegate* __strong window_delegate_; ElectronPreviewItem* __strong preview_item_; ElectronTouchBar* __strong touch_bar_; // The views::View that fills the client area. std::unique_ptr<RootViewMac> root_view_; bool fullscreen_before_kiosk_ = false; bool is_kiosk_ = false; bool zoom_to_page_width_ = false; absl::optional<gfx::Point> traffic_light_position_; // Trying to close an NSWindow during a fullscreen transition will cause the // window to lock up. Use this to track if CloseWindow was called during a // fullscreen transition, to defer the -[NSWindow close] call until the // transition is complete. bool has_deferred_window_close_ = false; NSInteger attention_request_id_ = 0; // identifier from requestUserAttention // The presentation options before entering kiosk mode. NSApplicationPresentationOptions kiosk_options_; // The "visualEffectState" option. VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow; // The visibility mode of window button controls when explicitly set through // setWindowButtonVisibility(). absl::optional<bool> window_button_visibility_; // Controls the position and visibility of window buttons. WindowButtonsProxy* __strong buttons_proxy_; std::unique_ptr<SkRegion> draggable_region_; // Maximizable window state; necessary for persistence through redraws. bool maximizable_ = true; bool user_set_bounds_maximized_ = false; // Simple (pre-Lion) Fullscreen Settings bool always_simple_fullscreen_ = false; bool is_simple_fullscreen_ = false; bool was_maximizable_ = false; bool was_movable_ = false; bool is_active_ = false; NSRect original_frame_; NSInteger original_level_; NSUInteger simple_fullscreen_mask_; NSRect default_frame_for_zoom_; std::string vibrancy_type_; // The presentation options before entering simple fullscreen mode. NSApplicationPresentationOptions simple_fullscreen_options_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
closed
electron/electron
https://github.com/electron/electron
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
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/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/browser.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" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorStyleBar) 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]]; } // -[NSWindow orderWindow] does not handle reordering for children // windows. Their order is fixed to the attachment order (the last attached // window is on the top). Therefore, work around it by re-parenting in our // desired order. void ReorderChildWindowAbove(NSWindow* child_window, NSWindow* other_window) { NSWindow* parent = [child_window parentWindow]; DCHECK(parent); // `ordered_children` sorts children windows back to front. NSArray<NSWindow*>* children = [[child_window parentWindow] childWindows]; std::vector<std::pair<NSInteger, NSWindow*>> ordered_children; for (NSWindow* child in children) ordered_children.push_back({[child orderedIndex], child}); std::sort(ordered_children.begin(), ordered_children.end(), std::greater<>()); // If `other_window` is nullptr, place `child_window` in front of // all other children windows. if (other_window == nullptr) other_window = ordered_children.back().second; if (child_window == other_window) return; for (NSWindow* child in children) [parent removeChildWindow:child]; const bool relative_to_parent = parent == other_window; if (relative_to_parent) [parent addChildWindow:child_window ordered:NSWindowAbove]; // Re-parent children windows in the desired order. for (auto [ordered_index, child] : ordered_children) { if (child != child_window && child != other_window) { [parent addChildWindow:child ordered:NSWindowAbove]; } else if (child == other_window && !relative_to_parent) { [parent addChildWindow:other_window ordered:NSWindowAbove]; [parent addChildWindow:child_window ordered:NSWindowAbove]; } } } } // 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_ = nil; }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_ = [[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_ = [[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::kNone) { SetHasDeferredWindowClose(true); return; } // Ensure we're detached from the parent window before closing. RemoveChildFromParentWindow(this); // 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() { RemoveChildFromParentWindow(this); [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; } DetachChildren(); // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; 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() { // It's possible for [window_ isZoomed] to be true // when the window is minimized or fullscreened. if (IsMinimized() || IsFullscreen()) return false; 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::RemoveChildWindow(NativeWindow* child) { child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); }); [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { if (parent()) parent()->RemoveChildWindow(child); } void NativeWindowMac::AttachChildren() { for (auto* child : child_windows_) { auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow(); if ([child_nswindow parentWindow] == window_) continue; // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [window_ addChildWindow:child_nswindow ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::DetachChildren() { DCHECK(child_windows_.size() == [[window_ childWindows] count]); // Hide all children before hiding/minimizing the window. // NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown() // will DCHECK otherwise. for (auto* child : child_windows_) { [child->GetNativeWindow().GetNativeNSWindow() orderOut:nil]; } } 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::kNone) { 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::kEntering : FullScreenTransitionState::kExiting; [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; if (!parent()) { [window_ orderWindow:NSWindowAbove relativeTo:window_id]; } else { NSWindow* other_window = [NSApp windowWithWindowNumber:window_id]; ReorderChildWindowAbove(window_, other_window); } return true; } void NativeWindowMac::MoveTop() { if (!parent()) [window_ orderWindow:NSWindowAbove relativeTo:0]; else ReorderChildWindowAbove(window_, nullptr); } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); // Right now, resizable and fullscreenable are decoupled in // documentation and on Windows/Linux. Chromium disables // fullscreenability if resizability is false on macOS as well // as disabling the maximize traffic light unless the window // is both resizable and maximizable. To work around this, we want // to match behavior on other platforms by disabiliting the maximize // button but keeping fullscreenability enabled. // TODO(codebytere): refactor this once we have a better solution. SetCanResize(resizable); if (!resizable) { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:false]; } else { SetFullScreenable(true); [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:IsFullScreenable()]; } } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::kNone; 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_ 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; fullscreen_before_kiosk_ = IsFullscreen(); if (!fullscreen_before_kiosk_) SetFullScreen(true); } else if (!kiosk && is_kiosk_) { is_kiosk_ = false; if (!fullscreen_before_kiosk_) 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 = std::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]; [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]; [progress_indicator setStyle:NSProgressIndicatorStyleBar]; [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 invoke // 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) { if (visibleOnFullScreen) { Browser::Get()->DockHide(); } else { Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate()); } } 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; } NSVisualEffectMaterial vibrancyType{}; if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } else 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 == "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]]; [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_ = [[ElectronTouchBar alloc] initWithDelegate:window_delegate_ 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::ShowAllTabs() { [window_ toggleTabOverview: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_ = [[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()) { 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* new_parent, bool attach) { if (is_modal()) return; // Do not remove/add if we are already properly attached. if (attach && new_parent && [window_ parentWindow] == new_parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. RemoveChildFromParentWindow(this); // Set new parent window. if (new_parent && attach) { new_parent->add_child_window(this); new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); } 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
38,939
[Bug]: Electron often crashes with SIGSEGV error on setParentWindow method
### 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 25.2.0 ### What operating system are you using? macOS ### Operating System Version macOS 13.0.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 23.3.8 ### Expected Behavior Second parent window and child window normally show and app continues to work without critical errors. ### Actual Behavior On `setParentWindow` method the app often crashes with following error: `Electron exited with signal SIGSEGV.` ### Testcase Gist URL https://gist.github.com/3b45265f63e8ebfd233665989b81cdab ### Additional Information Sometimes Electron correctly execute `setParentWindow` method.
https://github.com/electron/electron/issues/38939
https://github.com/electron/electron/pull/39062
fa5b1be6f3d6631c0404097b69ea81b4a1eab7f7
695fcf3cb265aa2b635e9bfdad4e0affe527c917
2023-06-27T15:46:41Z
c++
2023-07-26T14:47:32Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, 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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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. 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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); 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; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); 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-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } 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.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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); }); }); describe('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('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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') as Promise<[any, boolean]>; 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('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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') as [any, WebContents]; 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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('node: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') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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') as [any, BrowserWindow]; // 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') as Promise<[any, WebContents]>, 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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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') as Promise<[any, WebContents]>; 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') as Promise<[any, WebContents]>, 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('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); 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'); } }); // DISABLED-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('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('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); 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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('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(1000); 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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // 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') as Promise<[any, BrowserWindow]>; 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'); }); }); describe('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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); 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
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
patches/chromium/allow_disabling_blink_scheduler_throttling_per_renderview.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Mon, 18 May 2020 11:12:26 -0700 Subject: allow disabling blink scheduler throttling per RenderView This allows us to disable throttling for hidden windows. diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index 421a0b8ba291a944db62507d1004210555a1200c..09dd63d9f9a59d32dc9dd569aaa176a94dbfdfaa 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc @@ -710,6 +710,11 @@ void RenderViewHostImpl::SetBackgroundOpaque(bool opaque) { GetWidget()->GetAssociatedFrameWidget()->SetBackgroundOpaque(opaque); } +void RenderViewHostImpl::SetSchedulerThrottling(bool allowed) { + if (auto& broadcast = GetAssociatedPageBroadcast()) + broadcast->SetSchedulerThrottling(allowed); +} + bool RenderViewHostImpl::IsMainFrameActive() { return is_active(); } diff --git a/content/browser/renderer_host/render_view_host_impl.h b/content/browser/renderer_host/render_view_host_impl.h index 180abdc9f983887c83fd9d4a596472222e9ab472..00842717a7570561ee9e3eca11190ab5e1c76fb8 100644 --- a/content/browser/renderer_host/render_view_host_impl.h +++ b/content/browser/renderer_host/render_view_host_impl.h @@ -136,6 +136,7 @@ class CONTENT_EXPORT RenderViewHostImpl void EnablePreferredSizeMode() override; void WriteIntoTrace(perfetto::TracedProto<TraceProto> context) const override; + void SetSchedulerThrottling(bool allowed) override; void SendWebPreferencesToRenderer(); void SendRendererPreferencesToRenderer( const blink::RendererPreferences& preferences); diff --git a/content/public/browser/render_view_host.h b/content/public/browser/render_view_host.h index 9979c25ecd57e68331b628a518368635db5c2027..f65bfbbb663a5bb0511ffa389d3163e0fdeb4d1f 100644 --- a/content/public/browser/render_view_host.h +++ b/content/public/browser/render_view_host.h @@ -76,6 +76,9 @@ class CONTENT_EXPORT RenderViewHost { virtual void WriteIntoTrace( perfetto::TracedProto<TraceProto> context) const = 0; + // Disable/Enable scheduler throttling. + virtual void SetSchedulerThrottling(bool allowed) {} + private: // This interface should only be implemented inside content. friend class RenderViewHostImpl; diff --git a/content/test/test_page_broadcast.h b/content/test/test_page_broadcast.h index 73c0f64aa84061381a98ba60906835258f881468..41bdf7e231eca4617dbe53737a3925039bf77c4f 100644 --- a/content/test/test_page_broadcast.h +++ b/content/test/test_page_broadcast.h @@ -45,6 +45,7 @@ class TestPageBroadcast : public blink::mojom::PageBroadcast { override; void UpdatePageBrowsingContextGroup(const blink::BrowsingContextGroupInfo& browsing_context_group_info) override; + void SetSchedulerThrottling(bool allowed) override {} mojo::AssociatedReceiver<blink::mojom::PageBroadcast> receiver_; }; diff --git a/third_party/blink/public/mojom/page/page.mojom b/third_party/blink/public/mojom/page/page.mojom index d3877e946b1d65eba5bb45efe786fbcc7925ca6e..73bd5056baf7e4278b7260e550e2b8516be72f20 100644 --- a/third_party/blink/public/mojom/page/page.mojom +++ b/third_party/blink/public/mojom/page/page.mojom @@ -155,4 +155,7 @@ interface PageBroadcast { // in `browsing_context_group_info`. UpdatePageBrowsingContextGroup( blink.mojom.BrowsingContextGroupInfo browsing_context_group_info); + + // Whether to enable the Renderer scheduler background throttling. + SetSchedulerThrottling(bool allowed); }; diff --git a/third_party/blink/public/web/web_view.h b/third_party/blink/public/web/web_view.h index 8a18ecf567cd3a6a2fb1627083a5544a93198bf4..6bb4074e033e045de164bc776f75f152ea7be16f 100644 --- a/third_party/blink/public/web/web_view.h +++ b/third_party/blink/public/web/web_view.h @@ -371,6 +371,7 @@ class BLINK_EXPORT WebView { // Scheduling ----------------------------------------------------------- virtual PageScheduler* Scheduler() const = 0; + virtual void SetSchedulerThrottling(bool allowed) {} // Visibility ----------------------------------------------------------- diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 79c3ac1ae8f9a5c643fdf3f8772084afdb8ea0d2..8f834dd2d0eb89b896b704045d7bcee53bd08ec9 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc @@ -3853,13 +3853,21 @@ PageScheduler* WebViewImpl::Scheduler() const { return GetPage()->GetPageScheduler(); } +void WebViewImpl::SetSchedulerThrottling(bool allowed) { + DCHECK(GetPage()); + scheduler_throttling_allowed_ = allowed; + GetPage()->GetPageScheduler()->SetPageVisible(allowed ? + (GetVisibilityState() == mojom::blink::PageVisibilityState::kVisible) : true); +} + void WebViewImpl::SetVisibilityState( mojom::blink::PageVisibilityState visibility_state, bool is_initial_state) { DCHECK(GetPage()); GetPage()->SetVisibilityState(visibility_state, is_initial_state); GetPage()->GetPageScheduler()->SetPageVisible( - visibility_state == mojom::blink::PageVisibilityState::kVisible); + scheduler_throttling_allowed_ ? + (visibility_state == mojom::blink::PageVisibilityState::kVisible) : true); // Notify observers of the change. if (!is_initial_state) { for (auto& observer : observers_) diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 6a180620e00c77d0f4be346d1296f62feb714abb..c0ccf14faa52ab190c5848e8e9b597bcf637d4c0 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h @@ -445,6 +445,7 @@ class CORE_EXPORT WebViewImpl final : public WebView, LocalDOMWindow* PagePopupWindow() const; PageScheduler* Scheduler() const override; + void SetSchedulerThrottling(bool allowed) override; void SetVisibilityState(mojom::blink::PageVisibilityState visibility_state, bool is_initial_state) override; mojom::blink::PageVisibilityState GetVisibilityState() override; @@ -909,6 +910,8 @@ class CORE_EXPORT WebViewImpl final : public WebView, // If true, we send IPC messages when |preferred_size_| changes. bool send_preferred_size_changes_ = false; + bool scheduler_throttling_allowed_ = true; + // Whether the preferred size may have changed and |UpdatePreferredSize| needs // to be called. bool needs_preferred_size_update_ = true;
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
patches/chromium/extend_apply_webpreferences.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Mon, 8 Mar 2021 16:27:39 -0800 Subject: extend ApplyWebPreferences with Electron-specific logic background_color can be updated at runtime, as such we need to apply the new background color to the WebView in the ApplyPreferences method. There is no current way to attach an observer to these prefs so patching is our only option. Ideally we could add an embedder observer pattern here but that can be done in future work. diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 8f834dd2d0eb89b896b704045d7bcee53bd08ec9..cda2b89e88cb1358a8277c0f67903173d43bb5c3 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc @@ -165,6 +165,7 @@ #include "third_party/blink/renderer/core/view_transition/view_transition_supplement.h" #include "third_party/blink/renderer/platform/fonts/font_cache.h" #include "third_party/blink/renderer/platform/fonts/generic_font_family_settings.h" +#include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" @@ -1771,6 +1772,7 @@ void WebView::ApplyWebPreferences(const web_pref::WebPreferences& prefs, #if BUILDFLAG(IS_MAC) web_view_impl->SetMaximumLegibleScale( prefs.default_maximum_page_scale_factor); + SetUseExternalPopupMenus(!prefs.offscreen); #endif #if BUILDFLAG(IS_WIN)
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, 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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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. 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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); 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; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); 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-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } 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.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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); }); }); describe('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('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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') as Promise<[any, boolean]>; 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('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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') as [any, WebContents]; 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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('node: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') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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') as [any, BrowserWindow]; // 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') as Promise<[any, WebContents]>, 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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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') as Promise<[any, WebContents]>; 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') as Promise<[any, WebContents]>, 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('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); 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'); } }); // DISABLED-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('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('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); 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); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('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(1000); 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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // 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') as Promise<[any, BrowserWindow]>; 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'); }); }); describe('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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); 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
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/disabled-tests.json
[ "// NOTE: this file is used to disable tests in our test suite by their full title.", "BrowserWindow module BrowserWindow.loadURL(url) should emit did-fail-load event for files that do not exist", "BrowserWindow module document.visibilityState/hidden visibilityState remains visible if backgroundThrottling is disabled", "Menu module Menu.setApplicationMenu unsets a menu with null", "process module main process process.takeHeapSnapshot() returns true on success", "protocol module protocol.registerSchemesAsPrivileged cors-fetch disallows CORS and fetch requests when only supportFetchAPI is specified", "session module ses.cookies should set cookie for standard scheme", "webFrameMain module WebFrame.visibilityState should match window state", "reporting api sends a report for a deprecation", "chromium features SpeechSynthesis should emit lifecycle events" ]
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/fixtures/pages/visibilitychange.html
<html> <body> <script type="text/javascript" charset="utf-8"> const {ipcRenderer} = require('electron') ipcRenderer.send('pong', document.visibilityState, document.hidden) document.addEventListener('visibilitychange', function () { setTimeout(() => { ipcRenderer.send('pong', document.visibilityState, document.hidden) }, 500); }) </script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
patches/chromium/allow_disabling_blink_scheduler_throttling_per_renderview.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Mon, 18 May 2020 11:12:26 -0700 Subject: allow disabling blink scheduler throttling per RenderView This allows us to disable throttling for hidden windows. diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index 421a0b8ba291a944db62507d1004210555a1200c..09dd63d9f9a59d32dc9dd569aaa176a94dbfdfaa 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc @@ -710,6 +710,11 @@ void RenderViewHostImpl::SetBackgroundOpaque(bool opaque) { GetWidget()->GetAssociatedFrameWidget()->SetBackgroundOpaque(opaque); } +void RenderViewHostImpl::SetSchedulerThrottling(bool allowed) { + if (auto& broadcast = GetAssociatedPageBroadcast()) + broadcast->SetSchedulerThrottling(allowed); +} + bool RenderViewHostImpl::IsMainFrameActive() { return is_active(); } diff --git a/content/browser/renderer_host/render_view_host_impl.h b/content/browser/renderer_host/render_view_host_impl.h index 180abdc9f983887c83fd9d4a596472222e9ab472..00842717a7570561ee9e3eca11190ab5e1c76fb8 100644 --- a/content/browser/renderer_host/render_view_host_impl.h +++ b/content/browser/renderer_host/render_view_host_impl.h @@ -136,6 +136,7 @@ class CONTENT_EXPORT RenderViewHostImpl void EnablePreferredSizeMode() override; void WriteIntoTrace(perfetto::TracedProto<TraceProto> context) const override; + void SetSchedulerThrottling(bool allowed) override; void SendWebPreferencesToRenderer(); void SendRendererPreferencesToRenderer( const blink::RendererPreferences& preferences); diff --git a/content/public/browser/render_view_host.h b/content/public/browser/render_view_host.h index 9979c25ecd57e68331b628a518368635db5c2027..f65bfbbb663a5bb0511ffa389d3163e0fdeb4d1f 100644 --- a/content/public/browser/render_view_host.h +++ b/content/public/browser/render_view_host.h @@ -76,6 +76,9 @@ class CONTENT_EXPORT RenderViewHost { virtual void WriteIntoTrace( perfetto::TracedProto<TraceProto> context) const = 0; + // Disable/Enable scheduler throttling. + virtual void SetSchedulerThrottling(bool allowed) {} + private: // This interface should only be implemented inside content. friend class RenderViewHostImpl; diff --git a/content/test/test_page_broadcast.h b/content/test/test_page_broadcast.h index 73c0f64aa84061381a98ba60906835258f881468..41bdf7e231eca4617dbe53737a3925039bf77c4f 100644 --- a/content/test/test_page_broadcast.h +++ b/content/test/test_page_broadcast.h @@ -45,6 +45,7 @@ class TestPageBroadcast : public blink::mojom::PageBroadcast { override; void UpdatePageBrowsingContextGroup(const blink::BrowsingContextGroupInfo& browsing_context_group_info) override; + void SetSchedulerThrottling(bool allowed) override {} mojo::AssociatedReceiver<blink::mojom::PageBroadcast> receiver_; }; diff --git a/third_party/blink/public/mojom/page/page.mojom b/third_party/blink/public/mojom/page/page.mojom index d3877e946b1d65eba5bb45efe786fbcc7925ca6e..73bd5056baf7e4278b7260e550e2b8516be72f20 100644 --- a/third_party/blink/public/mojom/page/page.mojom +++ b/third_party/blink/public/mojom/page/page.mojom @@ -155,4 +155,7 @@ interface PageBroadcast { // in `browsing_context_group_info`. UpdatePageBrowsingContextGroup( blink.mojom.BrowsingContextGroupInfo browsing_context_group_info); + + // Whether to enable the Renderer scheduler background throttling. + SetSchedulerThrottling(bool allowed); }; diff --git a/third_party/blink/public/web/web_view.h b/third_party/blink/public/web/web_view.h index 8a18ecf567cd3a6a2fb1627083a5544a93198bf4..6bb4074e033e045de164bc776f75f152ea7be16f 100644 --- a/third_party/blink/public/web/web_view.h +++ b/third_party/blink/public/web/web_view.h @@ -371,6 +371,7 @@ class BLINK_EXPORT WebView { // Scheduling ----------------------------------------------------------- virtual PageScheduler* Scheduler() const = 0; + virtual void SetSchedulerThrottling(bool allowed) {} // Visibility ----------------------------------------------------------- diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 79c3ac1ae8f9a5c643fdf3f8772084afdb8ea0d2..8f834dd2d0eb89b896b704045d7bcee53bd08ec9 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc @@ -3853,13 +3853,21 @@ PageScheduler* WebViewImpl::Scheduler() const { return GetPage()->GetPageScheduler(); } +void WebViewImpl::SetSchedulerThrottling(bool allowed) { + DCHECK(GetPage()); + scheduler_throttling_allowed_ = allowed; + GetPage()->GetPageScheduler()->SetPageVisible(allowed ? + (GetVisibilityState() == mojom::blink::PageVisibilityState::kVisible) : true); +} + void WebViewImpl::SetVisibilityState( mojom::blink::PageVisibilityState visibility_state, bool is_initial_state) { DCHECK(GetPage()); GetPage()->SetVisibilityState(visibility_state, is_initial_state); GetPage()->GetPageScheduler()->SetPageVisible( - visibility_state == mojom::blink::PageVisibilityState::kVisible); + scheduler_throttling_allowed_ ? + (visibility_state == mojom::blink::PageVisibilityState::kVisible) : true); // Notify observers of the change. if (!is_initial_state) { for (auto& observer : observers_) diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 6a180620e00c77d0f4be346d1296f62feb714abb..c0ccf14faa52ab190c5848e8e9b597bcf637d4c0 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h @@ -445,6 +445,7 @@ class CORE_EXPORT WebViewImpl final : public WebView, LocalDOMWindow* PagePopupWindow() const; PageScheduler* Scheduler() const override; + void SetSchedulerThrottling(bool allowed) override; void SetVisibilityState(mojom::blink::PageVisibilityState visibility_state, bool is_initial_state) override; mojom::blink::PageVisibilityState GetVisibilityState() override; @@ -909,6 +910,8 @@ class CORE_EXPORT WebViewImpl final : public WebView, // If true, we send IPC messages when |preferred_size_| changes. bool send_preferred_size_changes_ = false; + bool scheduler_throttling_allowed_ = true; + // Whether the preferred size may have changed and |UpdatePreferredSize| needs // to be called. bool needs_preferred_size_update_ = true;
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
patches/chromium/extend_apply_webpreferences.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Samuel Attard <[email protected]> Date: Mon, 8 Mar 2021 16:27:39 -0800 Subject: extend ApplyWebPreferences with Electron-specific logic background_color can be updated at runtime, as such we need to apply the new background color to the WebView in the ApplyPreferences method. There is no current way to attach an observer to these prefs so patching is our only option. Ideally we could add an embedder observer pattern here but that can be done in future work. diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 8f834dd2d0eb89b896b704045d7bcee53bd08ec9..cda2b89e88cb1358a8277c0f67903173d43bb5c3 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc @@ -165,6 +165,7 @@ #include "third_party/blink/renderer/core/view_transition/view_transition_supplement.h" #include "third_party/blink/renderer/platform/fonts/font_cache.h" #include "third_party/blink/renderer/platform/fonts/generic_font_family_settings.h" +#include "third_party/blink/renderer/platform/graphics/color.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h" @@ -1771,6 +1772,7 @@ void WebView::ApplyWebPreferences(const web_pref::WebPreferences& prefs, #if BUILDFLAG(IS_MAC) web_view_impl->SetMaximumLegibleScale( prefs.default_maximum_page_scale_factor); + SetUseExternalPopupMenus(!prefs.offscreen); #endif #if BUILDFLAG(IS_WIN)
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as http from 'node:http'; import * as os from 'node:os'; import { AddressInfo } from 'node:net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, 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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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', () => { it('sets the correct class name on the prototype', () => { expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow'); }); 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. 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 allow access to id after destruction', async () => { const closed = once(w, 'closed'); w.destroy(); await closed; expect(w.id).to.be.a('number'); }); 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; }); // DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it('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 not emit did-fail-load for a successfully loaded media file', async () => { w.webContents.on('did-fail-load', () => { expect.fail('did-fail-load should not emit on media file loads'); }); const mediaStarted = once(w.webContents, 'media-started-playing'); w.loadFile(path.join(fixtures, 'cat-spin.mp4')); await mediaStarted; }); 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-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else if (req.url === '/navigate-iframe') { res.end('<a href="/test">navigate iframe</a>'); } else if (req.url === '/navigate-iframe?navigated') { res.end('Successfully navigated'); } else if (req.url === '/navigate-iframe-immediately') { res.end(` <script type="text/javascript" charset="utf-8"> location.href += '?navigated' </script> `); } else if (req.url === '/navigate-iframe-immediately?navigated') { res.end('Successfully navigated'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-frame-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-frame-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('can be prevented when navigating subframe', (done) => { let willNavigate = false; w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { if (isMainFrame) return; w.webContents.once('will-frame-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { const frame = webFrameMain.fromId(frameProcessId, frameRoutingId); expect(frame).to.not.be.undefined(); if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true(); done(); } catch (e) { done(e); } } }); }); w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`); }); 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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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-frame-navigate', (e) => { e.preventDefault(); resolve(e.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 () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await setTimeout(1000); let willFrameNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willFrameNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willFrameNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.true(); }); it('is triggered when a cross-origin iframe navigates itself', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`); await setTimeout(1000); let willNavigateEmitted = false; let isMainFrameValue; w.webContents.on('will-frame-navigate', (event) => { willNavigateEmitted = true; isMainFrameValue = event.isMainFrame; }); const didNavigatePromise = once(w.webContents, 'did-frame-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await didNavigatePromise; expect(willNavigateEmitted).to.be.true(); expect(isMainFrameValue).to.be.false(); }); it('can cancel when a cross-origin iframe navigates itself', async () => { }); }); 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('ordering', () => { let server = null as unknown as http.Server; let url = null as unknown as string; const navigationEvents = [ 'did-start-navigation', 'did-navigate-in-page', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); } else if (req.url === '/redirect') { res.end('<a href="/redirect2">redirect</a>'); } else if (req.url === '/redirect2') { res.statusCode = 302; res.setHeader('location', url); res.end(); } else if (req.url === '/in-page') { res.end('<a href="#in-page">redirect</a><div id="in-page"></div>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-frame-navigate', 'did-navigate' ]; const allEvents = Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const timeout = setTimeout(1000); w.loadURL(url); await Promise.race([allEvents, timeout]); expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('for second navigation, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}navigate`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating with redirection, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'will-frame-navigate', 'will-navigate', 'will-redirect', 'did-redirect-navigation', 'did-frame-navigate', 'did-navigate' ]; w.loadURL(`${url}redirect`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); it('when navigating in-page, event order is consistent', async () => { const firedEvents: string[] = []; const expectedEventOrder = [ 'did-start-navigation', 'did-navigate-in-page' ]; w.loadURL(`${url}in-page`); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => once(w.webContents, event).then(() => firedEvents.push(event)) )); const navigationFinished = once(w.webContents, 'did-navigate-in-page'); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await navigationFinished; expect(firedEvents).to.deep.equal(expectedEventOrder); }); }); }); } 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.minimize()', () => { // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => { const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMinimized()).to.equal(true); 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); }); }); describe('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('correctly reports maximized state after maximizing then minimizing', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.equal(false); expect(w.isMinimized()).to.equal(true); }); it('correctly reports maximized state after maximizing then fullscreening', async () => { w.destroy(); w = new BrowserWindow({ show: false }); w.show(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.isMaximized()).to.equal(false); expect(w.isFullScreen()).to.equal(true); }); it('checks normal bounds for maximized transparent window', async () => { w.destroy(); w = new BrowserWindow({ transparent: true, show: false }); w.show(); const bounds = w.getNormalBounds(); const maximize = once(w, 'maximize'); w.maximize(); await maximize; 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.showAllTabs()', () => { it('does not throw', () => { expect(() => { w.showAllTabs(); }).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', async () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); const restored = once(w, 'restore'); w.restore(); await restored; 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') as Promise<[any, boolean]>; 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('titlebar'); w.setVibrancy('selection'); w.setVibrancy(null); w.setVibrancy('menu'); 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') as [any, WebContents]; 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-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); /* eslint-disable-next-line no-new */ new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); }).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('node: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') as [BrowserWindow, Electron.DidCreateWindowDetails]; 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') as [any, BrowserWindow]; // 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') as Promise<[any, WebContents]>, 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'); expect(test.nodeEvents).to.equal(true); expect(test.nodeTimers).to.equal(true); expect(test.nodeUrl).to.equal(true); 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') as Promise<[any, WebContents]>; 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') as Promise<[any, WebContents]>, 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('"defaultFontFamily" option', () => { it('can change the standard font family', async () => { const w = new BrowserWindow({ show: false, webPreferences: { defaultFontFamily: { standard: 'Impact' } } }); await w.loadFile(path.join(fixtures, 'pages', 'content.html')); const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true); expect(fontFamily).to.equal('Impact'); }); }); }); 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'); } }); // DISABLED-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('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('can handle child window close and reparent multiple times', async () => { const w = new BrowserWindow({ show: false }); let c: BrowserWindow | null; for (let i = 0; i < 5; i++) { c = new BrowserWindow({ show: false, parent: w }); const closed = once(c, 'closed'); c.close(); await closed; } await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(w, 'minimize'); w.minimize(); await minimized; expect(w.isVisible()).to.be.false('parent is visible'); expect(c.isVisible()).to.be.false('child is visible'); const restored = once(w, 'restore'); w.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const wShow = once(w, 'show'); const cShow = once(c, 'show'); w.show(); c.show(); await Promise.all([wShow, cShow]); const minimized = once(c, 'minimize'); c.minimize(); await minimized; expect(c.isVisible()).to.be.false('child is visible'); const restored = once(c, 'restore'); c.restore(); await restored; expect(w.isVisible()).to.be.true('parent is visible'); expect(c.isVisible()).to.be.true('child is visible'); }); 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); }); ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); c.setParentWindow(w1); expect(w1.getChildWindows().length).to.equal(1); const closed = once(w1, 'closed'); w1.destroy(); await closed; c.setParentWindow(w2); await setTimeout(); const children = w2.getChildWindows(); expect(children[0]).to.equal(c); }); }); 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')('when fullscreen state is changed', () => { it('correctly remembers state prior to fullscreen change', async () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); }); it('correctly remembers state prior to fullscreen change with autoHide', async () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); const enterFS = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; expect(w.fullScreen).to.be.true('not fullscreen'); const exitFS = once(w, 'leave-full-screen'); w.setFullScreen(false); await exitFS; expect(w.fullScreen).to.be.false('not fullscreen'); expect(w.isMenuBarVisible()).to.be.false('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.setKiosk(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = once(w, 'leave-full-screen'); w.setKiosk(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('should stay fullscreen if fullscreen before kiosk', async () => { const w = new BrowserWindow(); const enterFullScreen = once(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); w.setKiosk(true); w.setKiosk(false); // Wait enough time for a fullscreen change to take effect. await setTimeout(2000); expect(w.isFullScreen()).to.be.true('isFullScreen'); }); it('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(1000); 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(); }); it('should not call BrowserWindow show event', async () => { const w = new BrowserWindow({ show: false }); const shown = once(w, 'show'); w.show(); await shown; let showCalled = false; w.on('show', () => { showCalled = true; }); w.previewFile(__filename); await setTimeout(500); expect(showCalled).to.equal(false, 'should not have called show twice'); }); }); // 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') as Promise<[any, BrowserWindow]>; 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'); }); }); describe('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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; 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') as [any, Electron.Rectangle, Electron.NativeImage]; expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { const w = new BrowserWindow({ frame: false, transparent: true }); const maximize = once(w, 'maximize'); w.maximize(); await maximize; const minimize = once(w, 'minimize'); w.minimize(); await minimize; expect(w.isMaximized()).to.be.false(); expect(w.isMinimized()).to.be.true(); }); // 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(); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => { const display = screen.getPrimaryDisplay(); for (const transparent of [false, undefined]) { const window = new BrowserWindow({ ...display.bounds, transparent }); await once(window, 'show'); await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>'); await setTimeout(500); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); window.close(); // color-scheme is set to dark so background should not be white expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); } }); }); 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
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/disabled-tests.json
[ "// NOTE: this file is used to disable tests in our test suite by their full title.", "BrowserWindow module BrowserWindow.loadURL(url) should emit did-fail-load event for files that do not exist", "BrowserWindow module document.visibilityState/hidden visibilityState remains visible if backgroundThrottling is disabled", "Menu module Menu.setApplicationMenu unsets a menu with null", "process module main process process.takeHeapSnapshot() returns true on success", "protocol module protocol.registerSchemesAsPrivileged cors-fetch disallows CORS and fetch requests when only supportFetchAPI is specified", "session module ses.cookies should set cookie for standard scheme", "webFrameMain module WebFrame.visibilityState should match window state", "reporting api sends a report for a deprecation", "chromium features SpeechSynthesis should emit lifecycle events" ]
closed
electron/electron
https://github.com/electron/electron
39,165
[Bug]: visibility state can be changed to `hidden` when `backgroundThrottling` is disabled
### 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 25.3.1 ### What operating system are you using? macOS ### Operating System Version MacOS 13.4.1 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior According to the [API doc](https://www.electronjs.org/docs/latest/api/browser-window#page-visibility), When `backgroundThrottling` is `false, the `document.visibilityState` always return `visible` even if the window is minimized, occluded, or hidden. > If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden. ### Actual Behavior When `backgroundThrottling` is `false, the `document.visibilityState` always return `hidden` when the window is minimized, occluded, or hidden. ### Testcase Gist URL https://gist.github.com/xiaofeihan1/4aceba89108f9b1a5b6d577ddd50e565 ### Additional Information https://github.com/electron/electron/assets/107654914/f2b40385-8d51-42aa-a360-3537befe1797
https://github.com/electron/electron/issues/39165
https://github.com/electron/electron/pull/39223
c9bae5da8ef280e310d4c1d03ee94a169c704357
6df392162f1d29155e6d8d6f755de7e48c18e709
2023-07-20T07:09:11Z
c++
2023-07-28T08:48:25Z
spec/fixtures/pages/visibilitychange.html
<html> <body> <script type="text/javascript" charset="utf-8"> const {ipcRenderer} = require('electron') ipcRenderer.send('pong', document.visibilityState, document.hidden) document.addEventListener('visibilitychange', function () { setTimeout(() => { ipcRenderer.send('pong', document.visibilityState, document.hidden) }, 500); }) </script> </body> </html>
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/desktop-capturer.md
# desktopCapturer > Access information about media sources that can be used to capture audio and > video from the desktop using the [`navigator.mediaDevices.getUserMedia`][] API. Process: [Main](../glossary.md#main-process) The following example shows how to capture video from a desktop window whose title is `Electron`: ```javascript // In the main process. const { BrowserWindow, desktopCapturer } = require('electron') const mainWindow = new BrowserWindow() desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => { for (const source of sources) { if (source.name === 'Electron') { mainWindow.webContents.send('SET_SOURCE', source.id) return } } }) ``` ```javascript @ts-nocheck // In the preload script. const { ipcRenderer } = require('electron') ipcRenderer.on('SET_SOURCE', async (event, sourceId) => { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }) handleStream(stream) } catch (e) { handleError(e) } }) function handleStream (stream) { const video = document.querySelector('video') video.srcObject = stream video.onloadedmetadata = (e) => video.play() } function handleError (e) { console.log(e) } ``` To capture video from a source provided by `desktopCapturer` the constraints passed to [`navigator.mediaDevices.getUserMedia`][] must include `chromeMediaSource: 'desktop'`, and `audio: false`. To capture both audio and video from the entire desktop the constraints passed to [`navigator.mediaDevices.getUserMedia`][] must include `chromeMediaSource: 'desktop'`, for both `audio` and `video`, but should not include a `chromeMediaSourceId` constraint. ```javascript const constraints = { audio: { mandatory: { chromeMediaSource: 'desktop' } }, video: { mandatory: { chromeMediaSource: 'desktop' } } } ``` ## Methods The `desktopCapturer` module has the following methods: ### `desktopCapturer.getSources(options)` * `options` Object * `types` string[] - An array of strings that lists the types of desktop sources to be captured, available types are `screen` and `window`. * `thumbnailSize` [Size](structures/size.md) (optional) - The size that the media source thumbnail should be scaled to. Default is `150` x `150`. Set width or height to 0 when you do not need the thumbnails. This will save the processing time required for capturing the content of each window and screen. * `fetchWindowIcons` boolean (optional) - Set to true to enable fetching window icons. The default value is false. When false the appIcon property of the sources return null. Same if a source has the type screen. Returns `Promise<DesktopCapturerSource[]>` - Resolves with an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md) objects, each `DesktopCapturerSource` represents a screen or an individual window that can be captured. **Note** Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher, which can detected by [`systemPreferences.getMediaAccessStatus`][]. [`navigator.mediaDevices.getUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/MediaDevices/getUserMedia [`systemPreferences.getMediaAccessStatus`]: system-preferences.md#systempreferencesgetmediaaccessstatusmediatype-windows-macos ## Caveats `navigator.mediaDevices.getUserMedia` does not work on macOS for audio capture due to a fundamental limitation whereby apps that want to access the system's audio require a [signed kernel extension](https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/KernelExtensions/KernelExtensions.html). Chromium, and by extension Electron, does not provide this. It is possible to circumvent this limitation by capturing system audio with another macOS app like Soundflower and passing it through a virtual audio input device. This virtual device can then be queried with `navigator.mediaDevices.getUserMedia`.
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
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://learn.microsoft.com/en-us/windows/win32/uxguide/vis-icons ## 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, size)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `size` [Size](structures/size.md) - the desired width and height (positive numbers) of the thumbnail. Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). Note: The Windows implementation will ignore `size.height` and scale the height according to `size.width`. ### `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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
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. ### `session.fromPath(path[, options])` * `path` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from the absolute path as specified by the `path` string. When there is an existing `Session` with the same absolute path, it will be returned; otherwise a new `Session` instance will be created with `options`. The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided. To create a `Session` with `options`, you have to ensure the `Session` with the `path` 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 @ts-expect-error=[4] 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void} 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 * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.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 * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.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.resolveHost(host, [options])` * `host` string - Hostname to resolve. * `options` Object (optional) * `queryType` string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: * `A` - Fetch only A records * `AAAA` - Fetch only AAAA records. * `source` string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values: * `any` (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc * `system` - Results will only be retrieved from the system or OS, e.g. via the `getaddrinfo()` system call * `dns` - Results will only come from DNS queries * `mdns` - Results will only come from Multicast DNS queries * `localOnly` - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc. * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values: * `allowed` (default) - Results may come from the host cache if non-stale * `staleAllowed` - Results may come from the host cache even if stale (by expiration or network changes) * `disallowed` - Results will not come from the host cache. * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values: * `allow` (default) * `disable` Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. #### `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 const win = new BrowserWindow() // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. win.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. win.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. By default, requests made with `net.fetch` can be made to [custom protocols](protocol.md) as well as `file:`, and will trigger [webRequest](web-request.md) handlers if present. When the non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. ```js protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('<body>my app</body>') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } }) ``` #### `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. * `display-capture` - Request access to capture the screen via the [Screen Capture API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API). * `fullscreen` - Request control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `geolocation` - Request access to the user's location via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `idle-detection` - Request access to the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Request access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Request access to DRM protected content. * `midi` - Request MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Request the use of system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Request notification creation and the ability to display them in the user's system tray using the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification) * `pointerLock` - Request to directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `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. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `geolocation` - Access the user's geolocation data via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `fullscreen` - Control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `hid` - Access the HID protocol to manipulate HID devices via the [WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API). * `idle-detection` - Access the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Access to DRM protected content. * `midi` - Enable MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Use system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Configure and display desktop notifications to the user with the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification). * `openExternal` - Open links in external applications. * `pointerLock` - Directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `serial` - Read from and write to serial devices with the [Web Serial API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API). * `usb` - Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the [WebUSB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API). * `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. * `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md) and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder` to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers while recording). Default is `false`. 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) | [USBDevice](structures/usb-device.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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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(selectedDevice?.deviceId) }) }) ``` #### `ses.setUSBProtectedClassesHandler(handler)` * `handler` Function\<string[]> | null * `details` Object * `protectedClasses` string[] - The current list of protected USB classes. Possible class values are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface). The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined). To clear the handler, call `setUSBProtectedClassesHandler(null)`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setUSBProtectedClassesHandler((details) => { // Allow all classes: // return [] // Keep the current set of protected classes: // return details.protectedClasses // Selectively remove classes: return details.protectedClasses.filter((usbClass) => { // Exclude classes except for audio classes return usbClass.indexOf('audio') === -1 }) }) }) ``` #### `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, session } = require('electron') const path = require('path') function createWindow () { let bluetoothPinCallback = null const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) 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) }) // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) } 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[, options])` * `url` string * `options` Object (optional) * `headers` Record<string, string> (optional) - HTTP request headers. 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.whenReady().then(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(path.join(__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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Navigation Events Several events can be used to monitor navigations as they occur within a `webContents`. ### Document Navigations When a `webContents` navigates to another page (as opposed to an [in-page navigation](web-contents.md#in-page-navigation)), the following events will be fired. * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) * [`will-navigate`](web-contents.md#event-will-navigate) (only fired when main frame navigates) * [`will-redirect`](web-contents.md#event-will-redirect) (only fired when a redirect happens during navigation) * [`did-redirect-navigation`](web-contents.md#event-did-redirect-navigation) (only fired when a redirect happens during navigation) * [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) * [`did-navigate`](web-contents.md#event-did-navigate) (only fired when main frame navigates) Subsequent events will not fire if `event.preventDefault()` is called on any of the cancellable events. ### In-page Navigation In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order: * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`did-navigate-in-page`](web-contents.md#event-did-navigate-in-page) ### Frame Navigation The [`will-navigate`](web-contents.md#event-will-navigate) and [`did-navigate`](web-contents.md#event-did-navigate) events only fire when the [mainFrame](web-contents.md#contentsmainframe-readonly) navigates. If you want to also observe navigations in `<iframe>`s, use [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) and [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) events. ## 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 wc.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](structures/browser-window-options.md) - 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` or `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 - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. * `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 on the main frame. 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: 'will-frame-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. * `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. Emitted when a user or the page wants to start navigation in any frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. Unlike `will-navigate`, `will-frame-navigate` is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, `isMainFrame` will be `true`. 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: * `event` Event * `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 `pointer`, `crosshair`, `hand`, `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`, `m-panning-vertical`, `m-panning-horizontal`, `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`, `custom`, `null`, `drag-drop-none`, `drag-drop-move`, `drag-drop-copy`, `drag-drop-link`, `ns-no-resize`, `ew-no-resize`, `nesw-no-resize`, `nwse-no-resize`, or `default`. 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 a bluetooth device needs to be selected when a call to `navigator.bluetooth.requestDevice` is made. `callback` should be called with the `deviceId` of the device to be selected. Passing an empty string to `callback` will cancel the request. If an event listener is not added for this event, or if `event.preventDefault` is not called when handling this event, the first available device will be automatically selected. Due to the nature of bluetooth, scanning for devices when `navigator.bluetooth.requestDevice` is called may take time and will cause `select-bluetooth-device` to fire multiple times until `callback` is called with either a device id or an empty string to cancel the request. ```javascript title='main.js' const { app, BrowserWindow } = require('electron') let win = null 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) { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or cancel the request by calling the callback // with an empty string. 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](structures/web-preferences.md) - 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 win = new BrowserWindow() const options = { extraHeaders: 'pragma: no-cache\n' } win.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 const win = new BrowserWindow() 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 const win = new BrowserWindow() win.webContents.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) { win.webContents.forcefullyCrashRenderer() win.webContents.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 const win = new BrowserWindow() win.webContents.on('did-finish-load', () => { win.webContents.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 const win = new BrowserWindow() win.webContents.on('did-finish-load', async () => { const key = await win.webContents.insertCSS('html, body { background-color: #f00; }') win.webContents.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 const win = new BrowserWindow() win.webContents.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` 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 > const win = new BrowserWindow() > win.webContents.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.centerSelection()` Centers the current text selection 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.scrollToTop()` Scrolls to the top of the current `webContents`. #### `contents.scrollToBottom()` Scrolls to the bottom of the current `webContents`. #### `contents.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. Example: ```js const win = new BrowserWindow() // Adjusts the beginning of the selection 1 letter forward, // and the end of the selection 5 letters forward. win.webContents.adjustSelection({ start: 1, end: 5 }) // Adjusts the beginning of the selection 2 letters forward, // and the end of the selection 3 letters backward. win.webContents.adjustSelection({ start: 2, end: -3 }) ``` For a call of `win.webContents.adjustSelection({ start: 1, end: 5 })` Before: <img width="487" alt="Image Before Text Selection Adjustment" src="../images/web-contents-text-selection-before.png"/> After: <img width="487" alt="Image After Text Selection Adjustment" src="../images/web-contents-text-selection-after.png"/> #### `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 win = new BrowserWindow() win.webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) win.webContents.stopFindInPage('clearSelection') }) const requestId = win.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 win = new BrowserWindow() 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 win = new BrowserWindow() const { port1, port2 } = new MessageChannelMain() win.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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/webview-tag.md
# `<webview>` Tag ## Warning Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which is undergoing dramatic architectural changes. This impacts the stability of `webviews`, including rendering, navigation, and event routing. We currently recommend to not use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md), or an architecture that avoids embedded content altogether. ## Enabling By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For more information see the [BrowserWindow constructor docs](browser-window.md). ## Overview > Display external web content in an isolated frame and process. 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._ Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. An embedded page within your app controls how the guest content is laid out and rendered. Unlike an `iframe`, the `webview` runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content. **Note:** Most methods called on the webview from the host page require a synchronous call to the main process. ## Example To embed a web page in your app, add the `webview` tag to your app's embedder page (this is the app page that will display the guest content). In its simplest form, the `webview` tag includes the `src` of the web page and css styles that control the appearance of the `webview` container: ```html <webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview> ``` If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the `webview` methods. Here's sample code with two event listeners: one that listens for the web page to start loading, the other for the web page to stop loading, and displays a "loading..." message during the load time: ```html <script> onload = () => { const webview = document.querySelector('webview') const indicator = document.querySelector('.indicator') const loadstart = () => { indicator.innerText = 'loading...' } const loadstop = () => { indicator.innerText = '' } webview.addEventListener('did-start-loading', loadstart) webview.addEventListener('did-stop-loading', loadstop) } </script> ``` ## Internal implementation Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes). The `webview` tag is essentially a custom element using shadow DOM to wrap an `iframe` element inside it. So the behavior of `webview` is very similar to a cross-domain `iframe`, as examples: * When clicking into a `webview`, the page focus will move from the embedder frame to `webview`. * You can not add keyboard, mouse, and scroll event listeners to `webview`. * All reactions between the embedder frame and `webview` are asynchronous. ## CSS Styling Notes Please note that the `webview` tag's style uses `display:flex;` internally to ensure the child `iframe` element fills the full height and width of its `webview` container when used with traditional and flexbox layouts. Please do not overwrite the default `display:flex;` CSS property, unless specifying `display:inline-flex;` for inline layout. ## Tag Attributes The `webview` tag has the following attributes: ### `src` ```html <webview src="https://www.github.com/"></webview> ``` A `string` representing the visible URL. Writing to this attribute initiates top-level navigation. Assigning `src` its own value will reload the current page. The `src` attribute can also accept data URLs, such as `data:text/plain,Hello, world!`. ### `nodeintegration` ```html <webview src="http://www.google.com/" nodeintegration></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will have node integration and can use node APIs like `require` and `process` to access low level system resources. Node integration is disabled by default in the guest page. ### `nodeintegrationinsubframes` ```html <webview src="http://www.google.com/" nodeintegrationinsubframes></webview> ``` A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the `webview`. All your preloads will load for every iframe, you can use `process.isMainFrame` to determine if you are in the main frame or not. This option is disabled by default in the guest page. ### `plugins` ```html <webview src="https://www.github.com/" plugins></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will be able to use browser plugins. Plugins are disabled by default. ### `preload` ```html <!-- from a file --> <webview src="https://www.github.com/" preload="./test.js"></webview> <!-- or if you want to load from an asar archive --> <webview src="https://www.github.com/" preload="./app.asar/test.js"></webview> ``` A `string` that specifies a script that will be loaded before other scripts run in the guest page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual directories. When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing. ### `httpreferrer` ```html <webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview> ``` A `string` that sets the referrer URL for the guest page. ### `useragent` ```html <webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview> ``` A `string` that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the `setUserAgent` method to change the user agent. ### `disablewebsecurity` ```html <webview src="https://www.github.com/" disablewebsecurity></webview> ``` A `boolean`. When this attribute is present the guest page will have web security disabled. Web security is enabled by default. This value can only be modified before the first navigation. ### `partition` ```html <webview src="https://github.com" partition="persist:github"></webview> <webview src="https://electronjs.org" partition="electron"></webview> ``` A `string` that sets the session used by the page. 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. By assigning the same `partition`, multiple pages can share the same session. If the `partition` is unset then default session of the app will be used. This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. ### `allowpopups` ```html <webview src="https://www.github.com/" allowpopups></webview> ``` A `boolean`. When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default. ### `webpreferences` ```html <webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview> ``` A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview. The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions). The string follows the same format as the features string in `window.open`. A name by itself is given a `true` boolean value. A preference can be set to another value by including an `=`, followed by the value. Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`. ### `enableblinkfeatures` ```html <webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ### `disableblinkfeatures` ```html <webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ## Methods The `webview` tag has the following methods: **Note:** The webview element must be loaded before using the methods. **Example** ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('dom-ready', () => { webview.openDevTools() }) ``` ### `<webview>.loadURL(url[, options])` * `url` URL * `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`](webview-tag.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](webview-tag.md#event-did-fail-load)). Loads the `url` in the webview, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. ### `<webview>.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. ### `<webview>.getURL()` Returns `string` - The URL of guest page. ### `<webview>.getTitle()` Returns `string` - The title of guest page. ### `<webview>.isLoading()` Returns `boolean` - Whether guest page is still loading resources. ### `<webview>.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. ### `<webview>.isWaitingForResponse()` Returns `boolean` - Whether the guest page is waiting for a first-response for the main resource of the page. ### `<webview>.stop()` Stops any pending navigation. ### `<webview>.reload()` Reloads the guest page. ### `<webview>.reloadIgnoringCache()` Reloads the guest page and ignores cache. ### `<webview>.canGoBack()` Returns `boolean` - Whether the guest page can go back. ### `<webview>.canGoForward()` Returns `boolean` - Whether the guest page can go forward. ### `<webview>.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the guest page can go to `offset`. ### `<webview>.clearHistory()` Clears the navigation history. ### `<webview>.goBack()` Makes the guest page go back. ### `<webview>.goForward()` Makes the guest page go forward. ### `<webview>.goToIndex(index)` * `index` Integer Navigates to the specified absolute index. ### `<webview>.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". ### `<webview>.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. ### `<webview>.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for the guest page. ### `<webview>.getUserAgent()` Returns `string` - The user agent for guest page. ### `<webview>.insertCSS(css)` * `css` string Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `<webview>.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ### `<webview>.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 `<webview>.insertCSS(css)`. ### `<webview>.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default `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. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require user action, can take advantage of this option for automation. ### `<webview>.openDevTools()` Opens a DevTools window for guest page. ### `<webview>.closeDevTools()` Closes the DevTools window of guest page. ### `<webview>.isDevToolsOpened()` Returns `boolean` - Whether guest page has a DevTools window attached. ### `<webview>.isDevToolsFocused()` Returns `boolean` - Whether DevTools window of guest page is focused. ### `<webview>.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`) of guest page. ### `<webview>.inspectSharedWorker()` Opens the DevTools for the shared worker context present in the guest page. ### `<webview>.inspectServiceWorker()` Opens the DevTools for the service worker context present in the guest page. ### `<webview>.setAudioMuted(muted)` * `muted` boolean Set guest page muted. ### `<webview>.isAudioMuted()` Returns `boolean` - Whether guest page has been muted. ### `<webview>.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. ### `<webview>.undo()` Executes editing command `undo` in page. ### `<webview>.redo()` Executes editing command `redo` in page. ### `<webview>.cut()` Executes editing command `cut` in page. ### `<webview>.copy()` Executes editing command `copy` in page. #### `<webview>.centerSelection()` Centers the current text selection in page. ### `<webview>.paste()` Executes editing command `paste` in page. ### `<webview>.pasteAndMatchStyle()` Executes editing command `pasteAndMatchStyle` in page. ### `<webview>.delete()` Executes editing command `delete` in page. ### `<webview>.selectAll()` Executes editing command `selectAll` in page. ### `<webview>.unselect()` Executes editing command `unselect` in page. #### `<webview>.scrollToTop()` Scrolls to the top of the current `<webview>`. #### `<webview>.scrollToBottom()` Scrolls to the bottom of the current `<webview>`. #### `<webview>.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. See [`webContents.adjustSelection`](web-contents.md#contentsadjustselectionoptions) for examples. ### `<webview>.replace(text)` * `text` string Executes editing command `replace` in page. ### `<webview>.replaceMisspelling(text)` * `text` string Executes editing command `replaceMisspelling` in page. ### `<webview>.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. ### `<webview>.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`](webview-tag.md#event-found-in-page) event. ### `<webview>.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`<webview>.findInPage`](#webviewfindinpagetext-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 `webview` with the provided `action`. ### `<webview>.print([options])` * `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. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` in microns. Returns `Promise<void>` Prints `webview`'s web page. Same as `webContents.print([options])`. ### `<webview>.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<Uint8Array>` - Resolves with the generated PDF data. Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`. ### `<webview>.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. ### `<webview>.send(channel, ...args)` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.send](web-contents.md#contentssendchannel-args) for examples. ### `<webview>.sendToFrame(frameId, channel, ...args)` * `frameId` \[number, number] - `[processId, frameId]` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for examples. ### `<webview>.sendInputEvent(event)` * `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Returns `Promise<void>` Sends an input `event` to the page. See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent) for detailed description of `event` object. ### `<webview>.setZoomFactor(factor)` * `factor` number - Zoom factor. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. ### `<webview>.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. ### `<webview>.getZoomFactor()` Returns `number` - the current zoom factor. ### `<webview>.getZoomLevel()` Returns `number` - the current zoom level. ### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. ### `<webview>.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. ### `<webview>.getWebContentsId()` Returns `number` - The WebContents ID of this `webview`. ## DOM Events The following DOM events are available to the `webview` tag: ### Event: 'load-commit' Returns: * `url` string * `isMainFrame` boolean Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. ### Event: 'did-finish-load' Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the `onload` event is dispatched. ### Event: 'did-fail-load' Returns: * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean This event is like `did-finish-load`, but fired when the load failed or was cancelled, e.g. `window.stop()` is invoked. ### Event: 'did-frame-finish-load' Returns: * `isMainFrame` boolean Fired when a frame has done navigation. ### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab starts spinning. ### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stops spinning. ### Event: 'did-attach' Fired when attached to the embedder web contents. ### Event: 'dom-ready' Fired when document in the given frame is loaded. ### Event: 'page-title-updated' Returns: * `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: * `favicons` string[] - Array of URLs. Fired when page receives favicon urls. ### Event: 'enter-html-full-screen' Fired when page enters fullscreen triggered by HTML API. ### Event: 'leave-html-full-screen' Fired when page leaves fullscreen triggered by HTML API. ### Event: 'console-message' Returns: * `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 Fired when the guest window logs a console message. The following example code forwards all log messages to the embedder's console without regard for log level or other properties. ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('console-message', (e) => { console.log('Guest page logged a message:', e.message) }) ``` ### Event: 'found-in-page' Returns: * `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 Fired when a result is available for [`webview.findInPage`](#webviewfindinpagetext-options) request. ```javascript @ts-expect-error=[3,6] const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` ### Event: 'will-navigate' Returns: * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does **NOT** have any effect. ### Event: 'will-frame-navigate' Returns: * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a user or the page wants to start navigation anywhere in the `<webview>` or any frames embedded within. 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 `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does **NOT** have any effect. ### Event: 'did-start-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. ### Event: 'did-redirect-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. ### Event: 'did-navigate' Returns: * `url` string Emitted when a 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: * `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: * `isMainFrame` boolean * `url` string Emitted when an in-page navigation happened. 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: 'close' Fired when the guest page attempts to close itself. The following example code navigates the `webview` to `about:blank` when the guest attempts to close itself. ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('close', () => { webview.src = 'about:blank' }) ``` ### Event: 'ipc-message' Returns: * `frameId` \[number, number] - pair of `[processId, frameId]`. * `channel` string * `args` any[] Fired when the guest page has sent an asynchronous message to embedder page. With `sendToHost` method and `ipc-message` event you can communicate between guest page and embedder page: ```javascript @ts-expect-error=[4,7] // In embedder page. const webview = document.querySelector('webview') webview.addEventListener('ipc-message', (event) => { console.log(event.channel) // Prints "pong" }) webview.send('ping') ``` ```javascript // In guest page. const { ipcRenderer } = require('electron') ipcRenderer.on('ping', () => { ipcRenderer.sendToHost('pong') }) ``` ### Event: 'crashed' Fired when the renderer process is crashed. ### Event: 'plugin-crashed' Returns: * `name` string * `version` string Fired when a plugin process is crashed. ### Event: 'destroyed' Fired when the WebContents is destroyed. ### 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: * `themeColor` string 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: * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. ### 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. [runtime-enabled-features]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5 [chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/ ### Event: 'context-menu' Returns: * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `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.
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
spec/api-session-spec.ts
import { expect } from 'chai'; import * as http from 'node:http'; import * as https from 'node:https'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as ChildProcess from 'node: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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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('session.fromPath(path)', () => { it('returns storage path of a session which was created with an absolute path', () => { const tmppath = require('electron').app.getPath('temp'); const ses = session.fromPath(tmppath); expect(ses.storagePath).to.equal(tmppath); }); }); 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: (Date.now()) / 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: (Date.now()) / 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 set cookie with an invalid domain attribute'); }); 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 set cookie with an invalid domain attribute'); }); 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: (Date.now()) / 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: (Date.now()) / 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); }); // DISABLED-FIXME it('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: (Date.now()) / 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: (Date.now()) / 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.resolveHost(host)', () => { let customSession: Electron.Session; beforeEach(async () => { customSession = session.fromPartition('resolvehost'); }); afterEach(() => { customSession = null as any; }); it('resolves ipv4.localhost2', async () => { const { endpoints } = await customSession.resolveHost('ipv4.localhost2'); expect(endpoints).to.be.a('array'); expect(endpoints).to.have.lengthOf(1); expect(endpoints[0].family).to.equal('ipv4'); expect(endpoints[0].address).to.equal('10.0.0.1'); }); it('fails to resolve AAAA record for ipv4.localhost2', async () => { await expect(customSession.resolveHost('ipv4.localhost2', { queryType: 'AAAA' })) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); it('resolves ipv6.localhost2', async () => { const { endpoints } = await customSession.resolveHost('ipv6.localhost2'); expect(endpoints).to.be.a('array'); expect(endpoints).to.have.lengthOf(1); expect(endpoints[0].family).to.equal('ipv6'); expect(endpoints[0].address).to.equal('::1'); }); it('fails to resolve A record for ipv6.localhost2', async () => { await expect(customSession.resolveHost('notfound.localhost2', { queryType: 'A' })) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); it('fails to resolve notfound.localhost2', async () => { await expect(customSession.resolveHost('notfound.localhost2')) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); }); 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(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(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 session.downloadURL with a valid auth header', async () => { const server = http.createServer((req, res) => { const { authorization } = req.headers; if (!authorization || authorization !== 'Basic i-am-an-auth-header') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); } }); const { port } = await listen(server); const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { session.defaultSession.once('will-download', (e, item) => { item.savePath = downloadFilePath; item.on('done', () => { try { resolve(item); } catch {} }); }); }); session.defaultSession.downloadURL(`${url}:${port}`, { headers: { Authorization: 'Basic i-am-an-auth-header' } }); const item = await downloadDone; expect(item.getState()).to.equal('completed'); expect(item.getFilename()).to.equal('mock.pdf'); 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); }); it('throws when session.downloadURL is called with invalid headers', () => { expect(() => { session.defaultSession.downloadURL(`${url}:${port}`, { // @ts-ignore this line is intentionally incorrect headers: 'i-am-a-bad-header' }); }).to.throw(/Invalid value for headers - must be an object/); }); it('can download using session.downloadURL with an invalid auth header', async () => { const server = http.createServer((req, res) => { const { authorization } = req.headers; if (!authorization || authorization !== 'Basic i-am-an-auth-header') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); } }); const { port } = await listen(server); const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { session.defaultSession.once('will-download', (_, item) => { item.savePath = downloadFilePath; item.on('done', (e, state) => { console.log(state); try { resolve(item); } catch {} }); }); }); session.defaultSession.downloadURL(`${url}:${port}`, { headers: { Authorization: 'wtf-is-this' } }); const item = await downloadFailed; expect(item.getState()).to.equal('interrupted'); expect(item.getReceivedBytes()).to.equal(0); expect(item.getTotalBytes()).to.equal(0); }); 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') as Promise<[any, Session]>; 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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
spec/ts-smoke/electron/main.ts
import { app, autoUpdater, BrowserWindow, contentTracing, dialog, desktopCapturer, globalShortcut, ipcMain, Menu, MenuItem, net, powerMonitor, powerSaveBlocker, protocol, Tray, screen, session, systemPreferences, webContents, TouchBar } from 'electron/main'; import { clipboard, crashReporter, nativeImage, shell } from 'electron/common'; import * as path from 'node:path'; // Quick start // https://github.com/electron/electron/blob/main/docs/tutorial/quick-start.md // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the javascript object is GCed. let mainWindow: Electron.BrowserWindow = null; // Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); // Check single instance app const gotLock = app.requestSingleInstanceLock(); if (!gotLock) { app.quit(); process.exit(0); } // This method will be called when Electron has done everything // initialization and ready for creating browser windows. app.whenReady().then(() => { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600 }); // and load the index.html of the app. mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer' }); mainWindow.webContents.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer' }); mainWindow.webContents.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer', postData: [{ type: 'rawData', bytes: Buffer.from([123]) }] }); mainWindow.webContents.openDevTools(); mainWindow.webContents.toggleDevTools(); mainWindow.webContents.openDevTools({ mode: 'detach' }); mainWindow.webContents.closeDevTools(); mainWindow.webContents.addWorkSpace('/path/to/workspace'); mainWindow.webContents.removeWorkSpace('/path/to/workspace'); const opened = mainWindow.webContents.isDevToolsOpened(); console.log('isDevToolsOpened', opened); const focused = mainWindow.webContents.isDevToolsFocused(); console.log('isDevToolsFocused', focused); // Emitted when the window is closed. mainWindow.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); mainWindow.webContents.setVisualZoomLevelLimits(50, 200); mainWindow.webContents.print({ silent: true, printBackground: false }); mainWindow.webContents.print(); mainWindow.webContents.printToPDF({ margins: { top: 1 }, printBackground: true, pageRanges: '1-3', landscape: true }).then((data: Buffer) => console.log(data)); mainWindow.webContents.printToPDF({}).then(data => console.log(data)); mainWindow.webContents.executeJavaScript('return true;').then((v: boolean) => console.log(v)); mainWindow.webContents.executeJavaScript('return true;', true).then((v: boolean) => console.log(v)); mainWindow.webContents.executeJavaScript('return true;', true); mainWindow.webContents.executeJavaScript('return true;', true).then((result: boolean) => console.log(result)); mainWindow.webContents.insertText('blah, blah, blah'); mainWindow.webContents.startDrag({ file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png') }); mainWindow.webContents.findInPage('blah'); mainWindow.webContents.findInPage('blah', { forward: true, matchCase: false }); mainWindow.webContents.stopFindInPage('clearSelection'); mainWindow.webContents.stopFindInPage('keepSelection'); mainWindow.webContents.stopFindInPage('activateSelection'); mainWindow.loadURL('https://github.com'); mainWindow.webContents.on('did-finish-load', function () { mainWindow.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page saved successfully'); }); }); try { mainWindow.webContents.debugger.attach('1.1'); } catch (err) { console.log('Debugger attach failed : ', err); } mainWindow.webContents.debugger.on('detach', function (event, reason) { console.log('Debugger detached due to : ', reason); }); mainWindow.webContents.debugger.on('message', function (event, method, params: any) { if (method === 'Network.requestWillBeSent') { if (params.request.url === 'https://www.github.com') { mainWindow.webContents.debugger.detach(); } } }); mainWindow.webContents.debugger.sendCommand('Network.enable'); mainWindow.webContents.capturePage().then(image => { console.log(image.toDataURL()); }); mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }).then(image => { console.log(image.toPNG()); }); }); app.commandLine.appendSwitch('enable-web-bluetooth'); app.whenReady().then(() => { mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault(); const result = (() => { for (const device of deviceList) { if (device.deviceName === 'test') { return device; } } return null; })(); if (!result) { callback(''); } else { callback(result.deviceId); } }); }); // Locale app.getLocale(); // Desktop environment integration app.addRecentDocument('/Users/USERNAME/Desktop/work.type'); app.clearRecentDocuments(); const dockMenu = Menu.buildFromTemplate([ <Electron.MenuItemConstructorOptions> { label: 'New Window', click: () => { console.log('New Window'); } }, <Electron.MenuItemConstructorOptions> { label: 'New Window with Settings', submenu: [ <Electron.MenuItemConstructorOptions> { label: 'Basic' }, <Electron.MenuItemConstructorOptions> { label: 'Pro' } ] }, <Electron.MenuItemConstructorOptions> { label: 'New Command...' }, <Electron.MenuItemConstructorOptions> { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' } ] } ]); app.dock.setMenu(dockMenu); app.dock.setBadge('foo'); const dockid = app.dock.bounce('informational'); app.dock.cancelBounce(dockid); app.dock.setIcon('/path/to/icon.png'); app.setBadgeCount(app.getBadgeCount() + 1); app.setUserTasks([ <Electron.Task> { program: process.execPath, arguments: '--new-window', iconPath: process.execPath, iconIndex: 0, title: 'New Window', description: 'Create a new window', workingDirectory: path.dirname(process.execPath) } ]); app.setUserTasks([]); 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', iconPath: process.execPath, iconIndex: 0, description: 'Runs Tool A', workingDirectory: path.dirname(process.execPath) }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', iconPath: process.execPath, iconIndex: 0, description: 'Runs Tool B', workingDirectory: path.dirname(process.execPath) }] }, { 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' }] } ]); if (app.isUnityRunning()) { console.log('unity running'); } if (app.isAccessibilitySupportEnabled()) { console.log('a11y running'); } app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false }); console.log(app.getLoginItemSettings().wasOpenedAtLogin); app.setAboutPanelOptions({ applicationName: 'Test', version: '1.2.3' }); // Online/Offline Event Detection // https://github.com/electron/electron/blob/main/docs/tutorial/online-offline-events.md let onlineStatusWindow: Electron.BrowserWindow; app.whenReady().then(() => { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false, vibrancy: 'sidebar' }); onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); }); app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled)); ipcMain.on('online-status-changed', (event, status: any) => { console.log(status); }); app.whenReady().then(() => { window = new BrowserWindow({ width: 800, height: 600, titleBarStyle: 'hiddenInset' }); window.loadURL('https://github.com'); }); // Supported command line switches // https://github.com/electron/electron/blob/main/docs/api/command-line-switches.md app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); app.commandLine.appendSwitch('vmodule', 'console=0'); // systemPreferences // https://github.com/electron/electron/blob/main/docs/api/system-preferences.md const browserOptions = { width: 1000, height: 800, transparent: false, frame: true }; // Make the window transparent only if the platform supports it. if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true; browserOptions.frame = false; } if (process.platform === 'win32') { systemPreferences.on('color-changed', () => { console.log('color changed'); }); systemPreferences.on('inverted-color-scheme-changed', (_, inverted) => console.log(inverted ? 'inverted' : 'not inverted')); console.log('Color for menu is', systemPreferences.getColor('menu')); } if (process.platform === 'darwin') { const value = systemPreferences.getUserDefault('Foo', 'string'); console.log(value); const value2 = systemPreferences.getUserDefault('Foo', 'boolean'); console.log(value2); } // Create the window. const win1 = new BrowserWindow(browserOptions); // Navigate. if (browserOptions.transparent) { win1.loadURL(`file://${__dirname}/index.html`); } else { // No transparency, so we load a fallback that uses basic styles. win1.loadURL(`file://${__dirname}/fallback.html`); } // app // https://github.com/electron/electron/blob/main/docs/api/app.md app.on('certificate-error', function (event, webContents, url, error, certificate, callback) { if (url === 'https://github.com') { // Verification logic. event.preventDefault(); callback(true); } else { callback(false); } }); app.on('select-client-certificate', function (event, webContents, url, list, callback) { event.preventDefault(); callback(list[0]); }); app.on('login', function (event, webContents, request, authInfo, callback) { event.preventDefault(); callback('username', 'secret'); }); const win2 = new BrowserWindow({ show: false }); win2.once('ready-to-show', () => { win2.show(); }); app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }); app.exit(0); // auto-updater // https://github.com/electron/electron/blob/main/docs/api/auto-updater.md autoUpdater.setFeedURL({ url: 'http://mycompany.com/myapp/latest?version=' + app.getVersion(), headers: { key: 'value' }, serverType: 'default' }); autoUpdater.checkForUpdates(); autoUpdater.quitAndInstall(); autoUpdater.on('error', (error) => { console.log('error', error); }); autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateURL) => { console.log('update-downloaded', releaseNotes, releaseName, releaseDate, updateURL); }); // BrowserWindow // https://github.com/electron/electron/blob/main/docs/api/browser-window.md let win3 = new BrowserWindow({ width: 800, height: 600, show: false }); win3.on('closed', () => { win3 = null; }); win3.loadURL('https://github.com'); win3.show(); const toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win3.setSheetOffset(toolbarRect.height); let window = new BrowserWindow(); window.setProgressBar(0.5); window.setRepresentedFilename('/etc/passwd'); window.setDocumentEdited(true); window.previewFile('/path/to/file'); window.previewFile('/path/to/file', 'Displayed Name'); window.setVibrancy('menu'); window.setVibrancy('titlebar'); window.setVibrancy('selection'); window.setVibrancy('popover'); window.setIcon('/path/to/icon'); // content-tracing // https://github.com/electron/electron/blob/main/docs/api/content-tracing.md const options = { categoryFilter: '*', traceOptions: 'record-until-full,enable-sampling' }; contentTracing.startRecording(options).then(() => { console.log('Tracing started'); setTimeout(function () { contentTracing.stopRecording('').then(path => { console.log(`Tracing data recorded to ${path}`); }); }, 5000); }); // dialog // https://github.com/electron/electron/blob/main/docs/api/dialog.md // variant without browserWindow dialog.showOpenDialogSync({ title: 'Testing showOpenDialog', defaultPath: '/var/log/syslog', filters: [{ name: '', extensions: [''] }], properties: ['openFile', 'openDirectory', 'multiSelections'] }); // variant with browserWindow dialog.showOpenDialog(win3, { title: 'Testing showOpenDialog', defaultPath: '/var/log/syslog', filters: [{ name: '', extensions: [''] }], properties: ['openFile', 'openDirectory', 'multiSelections'] }).then(ret => { console.log(ret); }); // variants without browserWindow dialog.showMessageBox({ message: 'test', type: 'warning' }); dialog.showMessageBoxSync({ message: 'test', type: 'error' }); // @ts-expect-error Invalid type value dialog.showMessageBox({ message: 'test', type: 'foo' }); // @ts-expect-error Invalid type value dialog.showMessageBoxSync({ message: 'test', type: 'foo' }); // variants with browserWindow dialog.showMessageBox(win3, { message: 'test', type: 'question' }); dialog.showMessageBoxSync(win3, { message: 'test', type: 'info' }); // @ts-expect-error Invalid type value dialog.showMessageBox(win3, { message: 'test', type: 'foo' }); // @ts-expect-error Invalid type value dialog.showMessageBoxSync(win3, { message: 'test', type: 'foo' }); // desktopCapturer // https://github.com/electron/electron/blob/main/docs/api/desktop-capturer.md ipcMain.handle('get-sources', (event, options) => desktopCapturer.getSources(options)); // global-shortcut // https://github.com/electron/electron/blob/main/docs/api/global-shortcut.md // Register a 'ctrl+x' shortcut listener. const ret = globalShortcut.register('ctrl+x', () => { console.log('ctrl+x is pressed'); }); if (!ret) { console.log('registration fails'); } // Check whether a shortcut is registered. console.log(globalShortcut.isRegistered('ctrl+x')); // Unregister a shortcut. globalShortcut.unregister('ctrl+x'); // Unregister all shortcuts. globalShortcut.unregisterAll(); // ipcMain // https://github.com/electron/electron/blob/main/docs/api/ipc-main.md ipcMain.on('asynchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.sender.send('asynchronous-reply', 'pong'); }); ipcMain.on('synchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.returnValue = 'pong'; }); ipcMain.on('synchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.returnValue = 'pong'; }); const winWindows = new BrowserWindow({ width: 800, height: 600, show: false, thickFrame: false, type: 'toolbar' }); console.log(winWindows.id); // menu-item // https://github.com/electron/electron/blob/main/docs/api/menu-item.md const menuItem = new MenuItem({}); menuItem.label = 'Hello World!'; menuItem.click = (passedMenuItem: Electron.MenuItem, browserWindow: Electron.BrowserWindow) => { console.log('click', passedMenuItem, browserWindow); }; // menu // https://github.com/electron/electron/blob/main/docs/api/menu.md let menu = new Menu(); menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true })); menu.insert(0, menuItem); console.log(menu.items); const pos = screen.getCursorScreenPoint(); menu.popup({ x: pos.x, y: pos.y }); // main.js const template = <Electron.MenuItemConstructorOptions[]> [ { label: 'Electron', submenu: [ { label: 'About Electron', role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide Electron', accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: () => { app.quit(); } } ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+Command+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', role: 'cut' }, { label: 'Copy', accelerator: 'Command+C', role: 'copy' }, { label: 'Paste', accelerator: 'Command+V', role: 'paste' }, { label: 'Select All', accelerator: 'Command+A', role: 'selectall' } ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'Command+R', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.reloadIgnoringCache(); } } }, { label: 'Toggle DevTools', accelerator: 'Alt+Command+I', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.toggleDevTools(); } } }, { type: 'separator' }, { label: 'Actual Size', accelerator: 'CmdOrCtrl+0', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.zoomLevel = 0; } } }, { label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', click: (item, focusedWindow) => { if (focusedWindow) { const { webContents } = focusedWindow; webContents.zoomLevel += 0.5; } } }, { label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', click: (item, focusedWindow) => { if (focusedWindow) { const { webContents } = focusedWindow; webContents.zoomLevel -= 0.5; } } } ] }, { label: 'Window', submenu: [ { label: 'Minimize', accelerator: 'Command+M', role: 'minimize' }, { label: 'Close', accelerator: 'Command+W', role: 'close' }, { type: 'separator' }, { label: 'Bring All to Front', role: 'front' } ] }, { label: 'Help', submenu: [] } ]; menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); // Must be called within app.whenReady().then(function(){ ... }); Menu.buildFromTemplate([ { label: '4', id: '4' }, { label: '5', id: '5', after: ['4'] }, { label: '1', id: '1', before: ['4'] }, { label: '2', id: '2' }, { label: '3', id: '3' } ]); Menu.buildFromTemplate([ { label: 'a' }, { label: '1' }, { label: 'b' }, { label: '2' }, { label: 'c' }, { label: '3' } ]); // All possible MenuItem roles Menu.buildFromTemplate([ { role: 'undo' }, { role: 'redo' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { role: 'reload' }, { role: 'forceReload' }, { role: 'toggleDevTools' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { role: 'togglefullscreen' }, { role: 'window' }, { role: 'minimize' }, { role: 'close' }, { role: 'help' }, { role: 'about' }, { role: 'services' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { role: 'quit' }, { role: 'startSpeaking' }, { role: 'stopSpeaking' }, { role: 'close' }, { role: 'minimize' }, { role: 'zoom' }, { role: 'front' }, { role: 'appMenu' }, { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }, { role: 'recentDocuments' }, { role: 'clearRecentDocuments' }, { role: 'toggleTabBar' }, { role: 'selectNextTab' }, { role: 'selectPreviousTab' }, { role: 'showAllTabs' }, { role: 'mergeAllWindows' }, { role: 'clearRecentDocuments' }, { role: 'moveTabToNewWindow' } ]); // net // https://github.com/electron/electron/blob/main/docs/api/net.md app.whenReady().then(() => { const request = net.request('https://github.com'); request.setHeader('Some-Custom-Header-Name', 'Some-Custom-Header-Value'); const header = request.getHeader('Some-Custom-Header-Name'); console.log('header', header); request.removeHeader('Some-Custom-Header-Name'); request.on('response', (response) => { console.log(`Status code: ${response.statusCode}`); console.log(`Status message: ${response.statusMessage}`); console.log(`Headers: ${JSON.stringify(response.headers)}`); console.log(`Http version: ${response.httpVersion}`); console.log(`Major Http version: ${response.httpVersionMajor}`); console.log(`Minor Http version: ${response.httpVersionMinor}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); response.on('end', () => { console.log('No more data in response.'); }); response.on('error', () => { console.log('"error" event emitted'); }); response.on('aborted', () => { console.log('"aborted" event emitted'); }); }); request.on('login', (authInfo, callback) => { callback('username', 'password'); }); request.on('finish', () => { console.log('"finish" event emitted'); }); request.on('abort', () => { console.log('"abort" event emitted'); }); request.on('error', () => { console.log('"error" event emitted'); }); request.write('Hello World!', 'utf-8'); request.end('Hello World!', 'utf-8'); request.abort(); }); // power-monitor // https://github.com/electron/electron/blob/main/docs/api/power-monitor.md app.whenReady().then(() => { powerMonitor.on('suspend', () => { console.log('The system is going to sleep'); }); powerMonitor.on('resume', () => { console.log('The system has resumed from sleep'); }); powerMonitor.on('on-ac', () => { console.log('The system changed to AC power'); }); powerMonitor.on('on-battery', () => { console.log('The system changed to battery power'); }); }); // power-save-blocker // https://github.com/electron/electron/blob/main/docs/api/power-save-blocker.md const id = powerSaveBlocker.start('prevent-display-sleep'); console.log(powerSaveBlocker.isStarted(id)); powerSaveBlocker.stop(id); // protocol // https://github.com/electron/electron/blob/main/docs/api/protocol.md app.whenReady().then(() => { protocol.registerSchemesAsPrivileged([{ scheme: 'https', privileges: { standard: true, allowServiceWorkers: true } }]); protocol.registerFileProtocol('atom', (request, callback) => { callback(`${__dirname}/${request.url}`); }); protocol.registerBufferProtocol('atom', (request, callback) => { callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') }); }); protocol.registerStringProtocol('atom', (request, callback) => { callback('Hello World!'); }); protocol.registerHttpProtocol('atom', (request, callback) => { callback({ url: request.url, method: request.method }); }); protocol.unregisterProtocol('atom'); const registered = protocol.isProtocolRegistered('atom'); console.log('isProtocolRegistered', registered); }); // tray // https://github.com/electron/electron/blob/main/docs/api/tray.md let appIcon: Electron.Tray = null; app.whenReady().then(() => { appIcon = new Tray('/path/to/my/icon'); const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }, { label: 'Item3', type: 'radio', checked: true }, { label: 'Item4', type: 'radio' } ]); appIcon.setTitle('title'); appIcon.setToolTip('This is my application.'); appIcon.setImage('/path/to/new/icon'); appIcon.setPressedImage('/path/to/new/icon'); appIcon.popUpContextMenu(contextMenu, { x: 100, y: 100 }); appIcon.setContextMenu(contextMenu); appIcon.setIgnoreDoubleClickEvents(true); appIcon.on('click', (event, bounds) => { console.log('click', event, bounds); }); appIcon.on('balloon-show', () => { console.log('balloon-show'); }); appIcon.displayBalloon({ title: 'Hello World!', content: 'This is the balloon content.', iconType: 'error', icon: 'path/to/icon', respectQuietTime: true, largeIcon: true, noSound: true }); }); // clipboard // https://github.com/electron/electron/blob/main/docs/api/clipboard.md clipboard.writeText('Example String'); clipboard.writeText('Example String', 'selection'); clipboard.writeBookmark('foo', 'http://example.com'); clipboard.writeBookmark('foo', 'http://example.com', 'selection'); clipboard.writeFindText('foo'); console.log(clipboard.readText('selection')); console.log(clipboard.readFindText()); console.log(clipboard.availableFormats()); console.log(clipboard.readBookmark().title); clipboard.clear(); clipboard.write({ html: '<html></html>', text: 'Hello World!', image: clipboard.readImage() }); // crash-reporter // https://github.com/electron/electron/blob/main/docs/api/crash-reporter.md crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', submitURL: 'https://your-domain.com/url-to-submit', uploadToServer: true, extra: { someKey: 'value' } }); console.log(crashReporter.getLastCrashReport()); console.log(crashReporter.getUploadedReports()); // nativeImage // https://github.com/electron/electron/blob/main/docs/api/native-image.md const appIcon2 = new Tray('/Users/somebody/images/icon.png'); appIcon2.destroy(); const window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); console.log(window2.id); const image = clipboard.readImage(); console.log(image.getSize()); const appIcon3 = new Tray(image); appIcon3.destroy(); const appIcon4 = new Tray('/Users/somebody/images/icon.png'); appIcon4.destroy(); const image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); console.log(image2.getSize()); // process // https://github.com/electron/electron/blob/main/docs/api/process.md console.log(process.versions.electron); console.log(process.versions.chrome); console.log(process.type); console.log(process.resourcesPath); console.log(process.mas); console.log(process.windowsStore); process.noAsar = true; process.crash(); process.hang(); process.setFdLimit(8192); // screen // https://github.com/electron/electron/blob/main/docs/api/screen.md app.whenReady().then(() => { const size = screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width: size.width, height: size.height }); }); app.whenReady().then(() => { const displays = screen.getAllDisplays(); let externalDisplay: any = null; for (const i in displays) { if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { externalDisplay = displays[i]; break; } } if (externalDisplay) { mainWindow = new BrowserWindow({ x: externalDisplay.bounds.x + 50, y: externalDisplay.bounds.y + 50 }); } screen.on('display-added', (event, display) => { console.log('display-added', display); }); screen.on('display-removed', (event, display) => { console.log('display-removed', display); }); screen.on('display-metrics-changed', (event, display, changes) => { console.log('display-metrics-changed', display, changes); }); }); // shell // https://github.com/electron/electron/blob/main/docs/api/shell.md shell.showItemInFolder('/home/user/Desktop/test.txt'); shell.trashItem('/home/user/Desktop/test.txt').then(() => {}); shell.openPath('/home/user/Desktop/test.txt').then(err => { if (err) console.log(err); }); shell.openExternal('https://github.com', { activate: false }).then(() => {}); shell.beep(); shell.writeShortcutLink('/home/user/Desktop/shortcut.lnk', 'update', shell.readShortcutLink('/home/user/Desktop/shortcut.lnk')); // cookies // https://github.com/electron/electron/blob/main/docs/api/cookies.md { // Query all cookies. session.defaultSession.cookies.get({}) .then(cookies => { console.log(cookies); }).catch((error: Error) => { console.log(error); }); // Query all cookies associated with a specific url. session.defaultSession.cookies.get({ url: 'http://www.github.com' }) .then(cookies => { console.log(cookies); }).catch((error: Error) => { console.log(error); }); // Set a cookie with the given cookie data; // may overwrite equivalent cookies if they exist. const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }; session.defaultSession.cookies.set(cookie) .then(() => { // success }, (error: Error) => { console.error(error); }); } // session // https://github.com/electron/electron/blob/main/docs/api/session.md session.defaultSession.on('will-download', (event, item, webContents) => { console.log('will-download', webContents.id); event.preventDefault(); require('got')(item.getURL()).then((data: any) => { require('node:fs').writeFileSync('/somewhere', data); }); }); // In the main process. session.defaultSession.on('will-download', (event, item, webContents) => { console.log('will-download', webContents.id); // Set the save path, making Electron not to prompt a save dialog. item.setSavePath('/tmp/save.pdf'); console.log(item.getSavePath()); console.log(item.getMimeType()); console.log(item.getFilename()); console.log(item.getTotalBytes()); item.on('updated', (_event, state) => { if (state === 'interrupted') { console.log('Download is interrupted but can be resumed'); } else if (state === 'progressing') { if (item.isPaused()) { console.log('Download is paused'); } else { console.log(`Received bytes: ${item.getReceivedBytes()}`); } } }); item.on('done', function (e, state) { if (state === 'completed') { console.log('Download successfully'); } else { console.log(`Download failed: ${state}`); } }); }); // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. session.defaultSession.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); // To emulate a network outage. session.defaultSession.enableNetworkEmulation({ offline: true }); session.defaultSession.setCertificateVerifyProc((request, callback) => { const { hostname } = request; if (hostname === 'github.com') { callback(0); } else { callback(-2); } }); session.defaultSession.setPermissionRequestHandler(function (webContents, permission, callback) { if (webContents.getURL() === 'github.com') { if (permission === 'notifications') { callback(false); return; } } callback(true); }); // 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('*'); // Modify the user agent for all requests to the following urls. const filter = { urls: ['https://*.github.com/*', '*://electron.github.io'] }; session.defaultSession.webRequest.onBeforeSendHeaders(filter, function (details: any, callback: any) { details.requestHeaders['User-Agent'] = 'MyAgent'; callback({ cancel: false, requestHeaders: details.requestHeaders }); }); app.whenReady().then(function () { const protocol = session.defaultSession.protocol; protocol.registerFileProtocol('atom', function (request, callback) { const url = request.url.substr(7); callback(path.normalize(`${__dirname}/${url}`)); }); }); // webContents // https://github.com/electron/electron/blob/main/docs/api/web-contents.md console.log(webContents.getAllWebContents()); console.log(webContents.getFocusedWebContents()); const win4 = new BrowserWindow({ webPreferences: { offscreen: true } }); win4.webContents.on('paint', (event, dirty, _image) => { console.log(dirty, _image.getBitmap()); }); win4.webContents.on('devtools-open-url', (event, url) => { console.log(url); }); win4.loadURL('http://github.com'); // TouchBar // https://github.com/electron/electron/blob/main/docs/api/touch-bar.md const touchBar = new TouchBar({ items: [ new TouchBar.TouchBarButton({ label: '' }), new TouchBar.TouchBarLabel({ label: '' }) ] }); mainWindow.setTouchBar(touchBar);
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/desktop-capturer.md
# desktopCapturer > Access information about media sources that can be used to capture audio and > video from the desktop using the [`navigator.mediaDevices.getUserMedia`][] API. Process: [Main](../glossary.md#main-process) The following example shows how to capture video from a desktop window whose title is `Electron`: ```javascript // In the main process. const { BrowserWindow, desktopCapturer } = require('electron') const mainWindow = new BrowserWindow() desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => { for (const source of sources) { if (source.name === 'Electron') { mainWindow.webContents.send('SET_SOURCE', source.id) return } } }) ``` ```javascript @ts-nocheck // In the preload script. const { ipcRenderer } = require('electron') ipcRenderer.on('SET_SOURCE', async (event, sourceId) => { try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: sourceId, minWidth: 1280, maxWidth: 1280, minHeight: 720, maxHeight: 720 } } }) handleStream(stream) } catch (e) { handleError(e) } }) function handleStream (stream) { const video = document.querySelector('video') video.srcObject = stream video.onloadedmetadata = (e) => video.play() } function handleError (e) { console.log(e) } ``` To capture video from a source provided by `desktopCapturer` the constraints passed to [`navigator.mediaDevices.getUserMedia`][] must include `chromeMediaSource: 'desktop'`, and `audio: false`. To capture both audio and video from the entire desktop the constraints passed to [`navigator.mediaDevices.getUserMedia`][] must include `chromeMediaSource: 'desktop'`, for both `audio` and `video`, but should not include a `chromeMediaSourceId` constraint. ```javascript const constraints = { audio: { mandatory: { chromeMediaSource: 'desktop' } }, video: { mandatory: { chromeMediaSource: 'desktop' } } } ``` ## Methods The `desktopCapturer` module has the following methods: ### `desktopCapturer.getSources(options)` * `options` Object * `types` string[] - An array of strings that lists the types of desktop sources to be captured, available types are `screen` and `window`. * `thumbnailSize` [Size](structures/size.md) (optional) - The size that the media source thumbnail should be scaled to. Default is `150` x `150`. Set width or height to 0 when you do not need the thumbnails. This will save the processing time required for capturing the content of each window and screen. * `fetchWindowIcons` boolean (optional) - Set to true to enable fetching window icons. The default value is false. When false the appIcon property of the sources return null. Same if a source has the type screen. Returns `Promise<DesktopCapturerSource[]>` - Resolves with an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md) objects, each `DesktopCapturerSource` represents a screen or an individual window that can be captured. **Note** Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher, which can detected by [`systemPreferences.getMediaAccessStatus`][]. [`navigator.mediaDevices.getUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/MediaDevices/getUserMedia [`systemPreferences.getMediaAccessStatus`]: system-preferences.md#systempreferencesgetmediaaccessstatusmediatype-windows-macos ## Caveats `navigator.mediaDevices.getUserMedia` does not work on macOS for audio capture due to a fundamental limitation whereby apps that want to access the system's audio require a [signed kernel extension](https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/KernelExtensions/KernelExtensions.html). Chromium, and by extension Electron, does not provide this. It is possible to circumvent this limitation by capturing system audio with another macOS app like Soundflower and passing it through a virtual audio input device. This virtual device can then be queried with `navigator.mediaDevices.getUserMedia`.
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
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://learn.microsoft.com/en-us/windows/win32/uxguide/vis-icons ## 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, size)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `size` [Size](structures/size.md) - the desired width and height (positive numbers) of the thumbnail. Returns `Promise<NativeImage>` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). Note: The Windows implementation will ignore `size.height` and scale the height according to `size.width`. ### `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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
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. ### `session.fromPath(path[, options])` * `path` string * `options` Object (optional) * `cache` boolean - Whether to enable cache. Returns `Session` - A session instance from the absolute path as specified by the `path` string. When there is an existing `Session` with the same absolute path, it will be returned; otherwise a new `Session` instance will be created with `options`. The call will throw an error if the path is not an absolute path. Additionally, an error will be thrown if an empty string is provided. To create a `Session` with `options`, you have to ensure the `Session` with the `path` 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 @ts-expect-error=[4] 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void} 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 * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.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 * `device` [USBDevice](structures/usb-device.md) * `webContents` [WebContents](web-contents.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.resolveHost(host, [options])` * `host` string - Hostname to resolve. * `options` Object (optional) * `queryType` string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: * `A` - Fetch only A records * `AAAA` - Fetch only AAAA records. * `source` string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values: * `any` (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc * `system` - Results will only be retrieved from the system or OS, e.g. via the `getaddrinfo()` system call * `dns` - Results will only come from DNS queries * `mdns` - Results will only come from Multicast DNS queries * `localOnly` - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc. * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values: * `allowed` (default) - Results may come from the host cache if non-stale * `staleAllowed` - Results may come from the host cache even if stale (by expiration or network changes) * `disallowed` - Results will not come from the host cache. * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values: * `allow` (default) * `disable` Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. #### `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 const win = new BrowserWindow() // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. win.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. win.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. By default, requests made with `net.fetch` can be made to [custom protocols](protocol.md) as well as `file:`, and will trigger [webRequest](web-request.md) handlers if present. When the non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. ```js protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('<body>my app</body>') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } }) ``` #### `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. * `display-capture` - Request access to capture the screen via the [Screen Capture API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API). * `fullscreen` - Request control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `geolocation` - Request access to the user's location via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `idle-detection` - Request access to the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Request access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Request access to DRM protected content. * `midi` - Request MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Request the use of system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Request notification creation and the ability to display them in the user's system tray using the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification) * `pointerLock` - Request to directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `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. * `clipboard-read` - Request access to read from the clipboard. * `clipboard-sanitized-write` - Request access to write to the clipboard. * `geolocation` - Access the user's geolocation data via the [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) * `fullscreen` - Control of the app's fullscreen state via the [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). * `hid` - Access the HID protocol to manipulate HID devices via the [WebHID API](https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API). * `idle-detection` - Access the user's idle state via the [IdleDetector API](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector). * `media` - Access to media devices such as camera, microphone and speakers. * `mediaKeySystem` - Access to DRM protected content. * `midi` - Enable MIDI access in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `midiSysex` - Use system exclusive messages in the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API). * `notifications` - Configure and display desktop notifications to the user with the [Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/notification). * `openExternal` - Open links in external applications. * `pointerLock` - Directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `serial` - Read from and write to serial devices with the [Web Serial API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API). * `usb` - Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the [WebUSB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API). * `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. * `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md) and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder` to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers while recording). Default is `false`. 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) | [USBDevice](structures/usb-device.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 @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} 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(selectedDevice?.deviceId) }) }) ``` #### `ses.setUSBProtectedClassesHandler(handler)` * `handler` Function\<string[]> | null * `details` Object * `protectedClasses` string[] - The current list of protected USB classes. Possible class values are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface). The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are: * `audio` * `audio-video` * `hid` * `mass-storage` * `smart-card` * `video` * `wireless` Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined). To clear the handler, call `setUSBProtectedClassesHandler(null)`. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow() win.webContents.session.setUSBProtectedClassesHandler((details) => { // Allow all classes: // return [] // Keep the current set of protected classes: // return details.protectedClasses // Selectively remove classes: return details.protectedClasses.filter((usbClass) => { // Exclude classes except for audio classes return usbClass.indexOf('audio') === -1 }) }) }) ``` #### `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, session } = require('electron') const path = require('path') function createWindow () { let bluetoothPinCallback = null const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) 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) }) // Listen for an IPC message from the renderer to get the response for the Bluetooth pairing. mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => { bluetoothPinCallback(response) }) } 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[, options])` * `url` string * `options` Object (optional) * `headers` Record<string, string> (optional) - HTTP request headers. 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.whenReady().then(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(path.join(__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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Navigation Events Several events can be used to monitor navigations as they occur within a `webContents`. ### Document Navigations When a `webContents` navigates to another page (as opposed to an [in-page navigation](web-contents.md#in-page-navigation)), the following events will be fired. * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) * [`will-navigate`](web-contents.md#event-will-navigate) (only fired when main frame navigates) * [`will-redirect`](web-contents.md#event-will-redirect) (only fired when a redirect happens during navigation) * [`did-redirect-navigation`](web-contents.md#event-did-redirect-navigation) (only fired when a redirect happens during navigation) * [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) * [`did-navigate`](web-contents.md#event-did-navigate) (only fired when main frame navigates) Subsequent events will not fire if `event.preventDefault()` is called on any of the cancellable events. ### In-page Navigation In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order: * [`did-start-navigation`](web-contents.md#event-did-start-navigation) * [`did-navigate-in-page`](web-contents.md#event-did-navigate-in-page) ### Frame Navigation The [`will-navigate`](web-contents.md#event-will-navigate) and [`did-navigate`](web-contents.md#event-did-navigate) events only fire when the [mainFrame](web-contents.md#contentsmainframe-readonly) navigates. If you want to also observe navigations in `<iframe>`s, use [`will-frame-navigate`](web-contents.md#event-will-frame-navigate) and [`did-frame-navigate`](web-contents.md#event-did-frame-navigate) events. ## 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 wc.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](structures/browser-window-options.md) - 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` or `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 - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. * `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 on the main frame. 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: 'will-frame-navigate' Returns: * `details` Event<> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. * `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. Emitted when a user or the page wants to start navigation in any frame. It can happen when the `window.location` object is changed or a user clicks a link in the page. Unlike `will-navigate`, `will-frame-navigate` is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, `isMainFrame` will be `true`. 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: * `event` Event * `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 `pointer`, `crosshair`, `hand`, `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`, `m-panning-vertical`, `m-panning-horizontal`, `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`, `custom`, `null`, `drag-drop-none`, `drag-drop-move`, `drag-drop-copy`, `drag-drop-link`, `ns-no-resize`, `ew-no-resize`, `nesw-no-resize`, `nwse-no-resize`, or `default`. 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 a bluetooth device needs to be selected when a call to `navigator.bluetooth.requestDevice` is made. `callback` should be called with the `deviceId` of the device to be selected. Passing an empty string to `callback` will cancel the request. If an event listener is not added for this event, or if `event.preventDefault` is not called when handling this event, the first available device will be automatically selected. Due to the nature of bluetooth, scanning for devices when `navigator.bluetooth.requestDevice` is called may take time and will cause `select-bluetooth-device` to fire multiple times until `callback` is called with either a device id or an empty string to cancel the request. ```javascript title='main.js' const { app, BrowserWindow } = require('electron') let win = null 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) { // The device wasn't found so we need to either wait longer (eg until the // device is turned on) or cancel the request by calling the callback // with an empty string. 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](structures/web-preferences.md) - 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 win = new BrowserWindow() const options = { extraHeaders: 'pragma: no-cache\n' } win.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 const win = new BrowserWindow() 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 const win = new BrowserWindow() win.webContents.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) { win.webContents.forcefullyCrashRenderer() win.webContents.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 const win = new BrowserWindow() win.webContents.on('did-finish-load', () => { win.webContents.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 const win = new BrowserWindow() win.webContents.on('did-finish-load', async () => { const key = await win.webContents.insertCSS('html, body { background-color: #f00; }') win.webContents.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 const win = new BrowserWindow() win.webContents.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` 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 > const win = new BrowserWindow() > win.webContents.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.centerSelection()` Centers the current text selection 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.scrollToTop()` Scrolls to the top of the current `webContents`. #### `contents.scrollToBottom()` Scrolls to the bottom of the current `webContents`. #### `contents.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. Example: ```js const win = new BrowserWindow() // Adjusts the beginning of the selection 1 letter forward, // and the end of the selection 5 letters forward. win.webContents.adjustSelection({ start: 1, end: 5 }) // Adjusts the beginning of the selection 2 letters forward, // and the end of the selection 3 letters backward. win.webContents.adjustSelection({ start: 2, end: -3 }) ``` For a call of `win.webContents.adjustSelection({ start: 1, end: 5 })` Before: <img width="487" alt="Image Before Text Selection Adjustment" src="../images/web-contents-text-selection-before.png"/> After: <img width="487" alt="Image After Text Selection Adjustment" src="../images/web-contents-text-selection-after.png"/> #### `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 win = new BrowserWindow() win.webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) win.webContents.stopFindInPage('clearSelection') }) const requestId = win.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 win = new BrowserWindow() 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 win = new BrowserWindow() const { port1, port2 } = new MessageChannelMain() win.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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
docs/api/webview-tag.md
# `<webview>` Tag ## Warning Electron's `webview` tag is based on [Chromium's `webview`][chrome-webview], which is undergoing dramatic architectural changes. This impacts the stability of `webviews`, including rendering, navigation, and event routing. We currently recommend to not use the `webview` tag and to consider alternatives, like `iframe`, [Electron's `BrowserView`](browser-view.md), or an architecture that avoids embedded content altogether. ## Enabling By default the `webview` tag is disabled in Electron >= 5. You need to enable the tag by setting the `webviewTag` webPreferences option when constructing your `BrowserWindow`. For more information see the [BrowserWindow constructor docs](browser-window.md). ## Overview > Display external web content in an isolated frame and process. 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._ Use the `webview` tag to embed 'guest' content (such as web pages) in your Electron app. The guest content is contained within the `webview` container. An embedded page within your app controls how the guest content is laid out and rendered. Unlike an `iframe`, the `webview` runs in a separate process than your app. It doesn't have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content. **Note:** Most methods called on the webview from the host page require a synchronous call to the main process. ## Example To embed a web page in your app, add the `webview` tag to your app's embedder page (this is the app page that will display the guest content). In its simplest form, the `webview` tag includes the `src` of the web page and css styles that control the appearance of the `webview` container: ```html <webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview> ``` If you want to control the guest content in any way, you can write JavaScript that listens for `webview` events and responds to those events using the `webview` methods. Here's sample code with two event listeners: one that listens for the web page to start loading, the other for the web page to stop loading, and displays a "loading..." message during the load time: ```html <script> onload = () => { const webview = document.querySelector('webview') const indicator = document.querySelector('.indicator') const loadstart = () => { indicator.innerText = 'loading...' } const loadstop = () => { indicator.innerText = '' } webview.addEventListener('did-start-loading', loadstart) webview.addEventListener('did-stop-loading', loadstop) } </script> ``` ## Internal implementation Under the hood `webview` is implemented with [Out-of-Process iframes (OOPIFs)](https://www.chromium.org/developers/design-documents/oop-iframes). The `webview` tag is essentially a custom element using shadow DOM to wrap an `iframe` element inside it. So the behavior of `webview` is very similar to a cross-domain `iframe`, as examples: * When clicking into a `webview`, the page focus will move from the embedder frame to `webview`. * You can not add keyboard, mouse, and scroll event listeners to `webview`. * All reactions between the embedder frame and `webview` are asynchronous. ## CSS Styling Notes Please note that the `webview` tag's style uses `display:flex;` internally to ensure the child `iframe` element fills the full height and width of its `webview` container when used with traditional and flexbox layouts. Please do not overwrite the default `display:flex;` CSS property, unless specifying `display:inline-flex;` for inline layout. ## Tag Attributes The `webview` tag has the following attributes: ### `src` ```html <webview src="https://www.github.com/"></webview> ``` A `string` representing the visible URL. Writing to this attribute initiates top-level navigation. Assigning `src` its own value will reload the current page. The `src` attribute can also accept data URLs, such as `data:text/plain,Hello, world!`. ### `nodeintegration` ```html <webview src="http://www.google.com/" nodeintegration></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will have node integration and can use node APIs like `require` and `process` to access low level system resources. Node integration is disabled by default in the guest page. ### `nodeintegrationinsubframes` ```html <webview src="http://www.google.com/" nodeintegrationinsubframes></webview> ``` A `boolean` for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the `webview`. All your preloads will load for every iframe, you can use `process.isMainFrame` to determine if you are in the main frame or not. This option is disabled by default in the guest page. ### `plugins` ```html <webview src="https://www.github.com/" plugins></webview> ``` A `boolean`. When this attribute is present the guest page in `webview` will be able to use browser plugins. Plugins are disabled by default. ### `preload` ```html <!-- from a file --> <webview src="https://www.github.com/" preload="./test.js"></webview> <!-- or if you want to load from an asar archive --> <webview src="https://www.github.com/" preload="./app.asar/test.js"></webview> ``` A `string` that specifies a script that will be loaded before other scripts run in the guest page. The protocol of script's URL must be `file:` (even when using `asar:` archives) because it will be loaded by Node's `require` under the hood, which treats `asar:` archives as virtual directories. When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing. ### `httpreferrer` ```html <webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview> ``` A `string` that sets the referrer URL for the guest page. ### `useragent` ```html <webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview> ``` A `string` that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the `setUserAgent` method to change the user agent. ### `disablewebsecurity` ```html <webview src="https://www.github.com/" disablewebsecurity></webview> ``` A `boolean`. When this attribute is present the guest page will have web security disabled. Web security is enabled by default. This value can only be modified before the first navigation. ### `partition` ```html <webview src="https://github.com" partition="persist:github"></webview> <webview src="https://electronjs.org" partition="electron"></webview> ``` A `string` that sets the session used by the page. 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. By assigning the same `partition`, multiple pages can share the same session. If the `partition` is unset then default session of the app will be used. This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. ### `allowpopups` ```html <webview src="https://www.github.com/" allowpopups></webview> ``` A `boolean`. When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default. ### `webpreferences` ```html <webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview> ``` A `string` which is a comma separated list of strings which specifies the web preferences to be set on the webview. The full list of supported preference strings can be found in [BrowserWindow](browser-window.md#new-browserwindowoptions). The string follows the same format as the features string in `window.open`. A name by itself is given a `true` boolean value. A preference can be set to another value by including an `=`, followed by the value. Special values `yes` and `1` are interpreted as `true`, while `no` and `0` are interpreted as `false`. ### `enableblinkfeatures` ```html <webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be enabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ### `disableblinkfeatures` ```html <webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview> ``` A `string` which is a list of strings which specifies the blink features to be disabled separated by `,`. The full list of supported feature strings can be found in the [RuntimeEnabledFeatures.json5][runtime-enabled-features] file. ## Methods The `webview` tag has the following methods: **Note:** The webview element must be loaded before using the methods. **Example** ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('dom-ready', () => { webview.openDevTools() }) ``` ### `<webview>.loadURL(url[, options])` * `url` URL * `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`](webview-tag.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](webview-tag.md#event-did-fail-load)). Loads the `url` in the webview, the `url` must contain the protocol prefix, e.g. the `http://` or `file://`. ### `<webview>.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. ### `<webview>.getURL()` Returns `string` - The URL of guest page. ### `<webview>.getTitle()` Returns `string` - The title of guest page. ### `<webview>.isLoading()` Returns `boolean` - Whether guest page is still loading resources. ### `<webview>.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. ### `<webview>.isWaitingForResponse()` Returns `boolean` - Whether the guest page is waiting for a first-response for the main resource of the page. ### `<webview>.stop()` Stops any pending navigation. ### `<webview>.reload()` Reloads the guest page. ### `<webview>.reloadIgnoringCache()` Reloads the guest page and ignores cache. ### `<webview>.canGoBack()` Returns `boolean` - Whether the guest page can go back. ### `<webview>.canGoForward()` Returns `boolean` - Whether the guest page can go forward. ### `<webview>.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the guest page can go to `offset`. ### `<webview>.clearHistory()` Clears the navigation history. ### `<webview>.goBack()` Makes the guest page go back. ### `<webview>.goForward()` Makes the guest page go forward. ### `<webview>.goToIndex(index)` * `index` Integer Navigates to the specified absolute index. ### `<webview>.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". ### `<webview>.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. ### `<webview>.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for the guest page. ### `<webview>.getUserAgent()` Returns `string` - The user agent for guest page. ### `<webview>.insertCSS(css)` * `css` string Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `<webview>.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ### `<webview>.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 `<webview>.insertCSS(css)`. ### `<webview>.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default `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. If `userGesture` is set, it will create the user gesture context in the page. HTML APIs like `requestFullScreen`, which require user action, can take advantage of this option for automation. ### `<webview>.openDevTools()` Opens a DevTools window for guest page. ### `<webview>.closeDevTools()` Closes the DevTools window of guest page. ### `<webview>.isDevToolsOpened()` Returns `boolean` - Whether guest page has a DevTools window attached. ### `<webview>.isDevToolsFocused()` Returns `boolean` - Whether DevTools window of guest page is focused. ### `<webview>.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`) of guest page. ### `<webview>.inspectSharedWorker()` Opens the DevTools for the shared worker context present in the guest page. ### `<webview>.inspectServiceWorker()` Opens the DevTools for the service worker context present in the guest page. ### `<webview>.setAudioMuted(muted)` * `muted` boolean Set guest page muted. ### `<webview>.isAudioMuted()` Returns `boolean` - Whether guest page has been muted. ### `<webview>.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. ### `<webview>.undo()` Executes editing command `undo` in page. ### `<webview>.redo()` Executes editing command `redo` in page. ### `<webview>.cut()` Executes editing command `cut` in page. ### `<webview>.copy()` Executes editing command `copy` in page. #### `<webview>.centerSelection()` Centers the current text selection in page. ### `<webview>.paste()` Executes editing command `paste` in page. ### `<webview>.pasteAndMatchStyle()` Executes editing command `pasteAndMatchStyle` in page. ### `<webview>.delete()` Executes editing command `delete` in page. ### `<webview>.selectAll()` Executes editing command `selectAll` in page. ### `<webview>.unselect()` Executes editing command `unselect` in page. #### `<webview>.scrollToTop()` Scrolls to the top of the current `<webview>`. #### `<webview>.scrollToBottom()` Scrolls to the bottom of the current `<webview>`. #### `<webview>.adjustSelection(options)` * `options` Object * `start` Number (optional) - Amount to shift the start index of the current selection. * `end` Number (optional) - Amount to shift the end index of the current selection. Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document. See [`webContents.adjustSelection`](web-contents.md#contentsadjustselectionoptions) for examples. ### `<webview>.replace(text)` * `text` string Executes editing command `replace` in page. ### `<webview>.replaceMisspelling(text)` * `text` string Executes editing command `replaceMisspelling` in page. ### `<webview>.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. ### `<webview>.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`](webview-tag.md#event-found-in-page) event. ### `<webview>.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`<webview>.findInPage`](#webviewfindinpagetext-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 `webview` with the provided `action`. ### `<webview>.print([options])` * `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. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` in microns. Returns `Promise<void>` Prints `webview`'s web page. Same as `webContents.print([options])`. ### `<webview>.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<Uint8Array>` - Resolves with the generated PDF data. Prints `webview`'s web page as PDF, Same as `webContents.printToPDF(options)`. ### `<webview>.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. ### `<webview>.send(channel, ...args)` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.send](web-contents.md#contentssendchannel-args) for examples. ### `<webview>.sendToFrame(frameId, channel, ...args)` * `frameId` \[number, number] - `[processId, frameId]` * `channel` string * `...args` any[] Returns `Promise<void>` Send an asynchronous message to renderer process via `channel`, you can also send arbitrary arguments. The renderer process can handle the message by listening to the `channel` event with the [`ipcRenderer`](ipc-renderer.md) module. See [webContents.sendToFrame](web-contents.md#contentssendtoframeframeid-channel-args) for examples. ### `<webview>.sendInputEvent(event)` * `event` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Returns `Promise<void>` Sends an input `event` to the page. See [webContents.sendInputEvent](web-contents.md#contentssendinputeventinputevent) for detailed description of `event` object. ### `<webview>.setZoomFactor(factor)` * `factor` number - Zoom factor. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. ### `<webview>.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. ### `<webview>.getZoomFactor()` Returns `number` - the current zoom factor. ### `<webview>.getZoomLevel()` Returns `number` - the current zoom level. ### `<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. ### `<webview>.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. ### `<webview>.getWebContentsId()` Returns `number` - The WebContents ID of this `webview`. ## DOM Events The following DOM events are available to the `webview` tag: ### Event: 'load-commit' Returns: * `url` string * `isMainFrame` boolean Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. ### Event: 'did-finish-load' Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the `onload` event is dispatched. ### Event: 'did-fail-load' Returns: * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean This event is like `did-finish-load`, but fired when the load failed or was cancelled, e.g. `window.stop()` is invoked. ### Event: 'did-frame-finish-load' Returns: * `isMainFrame` boolean Fired when a frame has done navigation. ### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab starts spinning. ### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stops spinning. ### Event: 'did-attach' Fired when attached to the embedder web contents. ### Event: 'dom-ready' Fired when document in the given frame is loaded. ### Event: 'page-title-updated' Returns: * `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: * `favicons` string[] - Array of URLs. Fired when page receives favicon urls. ### Event: 'enter-html-full-screen' Fired when page enters fullscreen triggered by HTML API. ### Event: 'leave-html-full-screen' Fired when page leaves fullscreen triggered by HTML API. ### Event: 'console-message' Returns: * `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 Fired when the guest window logs a console message. The following example code forwards all log messages to the embedder's console without regard for log level or other properties. ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('console-message', (e) => { console.log('Guest page logged a message:', e.message) }) ``` ### Event: 'found-in-page' Returns: * `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 Fired when a result is available for [`webview.findInPage`](#webviewfindinpagetext-options) request. ```javascript @ts-expect-error=[3,6] const webview = document.querySelector('webview') webview.addEventListener('found-in-page', (e) => { webview.stopFindInPage('keepSelection') }) const requestId = webview.findInPage('test') console.log(requestId) ``` ### Event: 'will-navigate' Returns: * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does **NOT** have any effect. ### Event: 'will-frame-navigate' Returns: * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a user or the page wants to start navigation anywhere in the `<webview>` or any frames embedded within. 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 `<webview>.loadURL` and `<webview>.back`. It is also not emitted during in-page navigation, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` does **NOT** have any effect. ### Event: 'did-start-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. ### Event: 'did-redirect-navigation' Returns: * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. ### Event: 'did-navigate' Returns: * `url` string Emitted when a 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: * `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: * `isMainFrame` boolean * `url` string Emitted when an in-page navigation happened. 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: 'close' Fired when the guest page attempts to close itself. The following example code navigates the `webview` to `about:blank` when the guest attempts to close itself. ```javascript @ts-expect-error=[3] const webview = document.querySelector('webview') webview.addEventListener('close', () => { webview.src = 'about:blank' }) ``` ### Event: 'ipc-message' Returns: * `frameId` \[number, number] - pair of `[processId, frameId]`. * `channel` string * `args` any[] Fired when the guest page has sent an asynchronous message to embedder page. With `sendToHost` method and `ipc-message` event you can communicate between guest page and embedder page: ```javascript @ts-expect-error=[4,7] // In embedder page. const webview = document.querySelector('webview') webview.addEventListener('ipc-message', (event) => { console.log(event.channel) // Prints "pong" }) webview.send('ping') ``` ```javascript // In guest page. const { ipcRenderer } = require('electron') ipcRenderer.on('ping', () => { ipcRenderer.sendToHost('pong') }) ``` ### Event: 'crashed' Fired when the renderer process is crashed. ### Event: 'plugin-crashed' Returns: * `name` string * `version` string Fired when a plugin process is crashed. ### Event: 'destroyed' Fired when the WebContents is destroyed. ### 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: * `themeColor` string 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: * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. ### 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. [runtime-enabled-features]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5 [chrome-webview]: https://developer.chrome.com/docs/extensions/reference/webviewTag/ ### Event: 'context-menu' Returns: * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `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.
closed
electron/electron
https://github.com/electron/electron
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
spec/api-session-spec.ts
import { expect } from 'chai'; import * as http from 'node:http'; import * as https from 'node:https'; import * as path from 'node:path'; import * as fs from 'node:fs'; import * as ChildProcess from 'node: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 'node:events'; import { setTimeout } from 'node:timers/promises'; 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('session.fromPath(path)', () => { it('returns storage path of a session which was created with an absolute path', () => { const tmppath = require('electron').app.getPath('temp'); const ses = session.fromPath(tmppath); expect(ses.storagePath).to.equal(tmppath); }); }); 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: (Date.now()) / 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: (Date.now()) / 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 set cookie with an invalid domain attribute'); }); 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 set cookie with an invalid domain attribute'); }); 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: (Date.now()) / 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: (Date.now()) / 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); }); // DISABLED-FIXME it('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: (Date.now()) / 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: (Date.now()) / 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.resolveHost(host)', () => { let customSession: Electron.Session; beforeEach(async () => { customSession = session.fromPartition('resolvehost'); }); afterEach(() => { customSession = null as any; }); it('resolves ipv4.localhost2', async () => { const { endpoints } = await customSession.resolveHost('ipv4.localhost2'); expect(endpoints).to.be.a('array'); expect(endpoints).to.have.lengthOf(1); expect(endpoints[0].family).to.equal('ipv4'); expect(endpoints[0].address).to.equal('10.0.0.1'); }); it('fails to resolve AAAA record for ipv4.localhost2', async () => { await expect(customSession.resolveHost('ipv4.localhost2', { queryType: 'AAAA' })) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); it('resolves ipv6.localhost2', async () => { const { endpoints } = await customSession.resolveHost('ipv6.localhost2'); expect(endpoints).to.be.a('array'); expect(endpoints).to.have.lengthOf(1); expect(endpoints[0].family).to.equal('ipv6'); expect(endpoints[0].address).to.equal('::1'); }); it('fails to resolve A record for ipv6.localhost2', async () => { await expect(customSession.resolveHost('notfound.localhost2', { queryType: 'A' })) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); it('fails to resolve notfound.localhost2', async () => { await expect(customSession.resolveHost('notfound.localhost2')) .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/); }); }); 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(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(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 session.downloadURL with a valid auth header', async () => { const server = http.createServer((req, res) => { const { authorization } = req.headers; if (!authorization || authorization !== 'Basic i-am-an-auth-header') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); } }); const { port } = await listen(server); const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { session.defaultSession.once('will-download', (e, item) => { item.savePath = downloadFilePath; item.on('done', () => { try { resolve(item); } catch {} }); }); }); session.defaultSession.downloadURL(`${url}:${port}`, { headers: { Authorization: 'Basic i-am-an-auth-header' } }); const item = await downloadDone; expect(item.getState()).to.equal('completed'); expect(item.getFilename()).to.equal('mock.pdf'); 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); }); it('throws when session.downloadURL is called with invalid headers', () => { expect(() => { session.defaultSession.downloadURL(`${url}:${port}`, { // @ts-ignore this line is intentionally incorrect headers: 'i-am-a-bad-header' }); }).to.throw(/Invalid value for headers - must be an object/); }); it('can download using session.downloadURL with an invalid auth header', async () => { const server = http.createServer((req, res) => { const { authorization } = req.headers; if (!authorization || authorization !== 'Basic i-am-an-auth-header') { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); res.end(); } else { res.writeHead(200, { 'Content-Length': mockPDF.length, 'Content-Type': 'application/pdf', 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition }); res.end(mockPDF); } }); const { port } = await listen(server); const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { session.defaultSession.once('will-download', (_, item) => { item.savePath = downloadFilePath; item.on('done', (e, state) => { console.log(state); try { resolve(item); } catch {} }); }); }); session.defaultSession.downloadURL(`${url}:${port}`, { headers: { Authorization: 'wtf-is-this' } }); const item = await downloadFailed; expect(item.getState()).to.equal('interrupted'); expect(item.getReceivedBytes()).to.equal(0); expect(item.getTotalBytes()).to.equal(0); }); 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') as Promise<[any, Session]>; 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
38,339
Improve Type Union Typings in the Docs
[The phrasings that `electron/docs-parser` recognizes for string union types](https://github.com/electron/docs-parser/blob/c56164b4cebcf010306e0458729bf179bf69e650/src/markdown-helpers.ts#L459) is fairly narrow, and it looks like there's a handful of places in the docs where the phrasing is not being picked up as string union types. Fix these and add smoke tests with `// @ts-expect-error` to ensure type unions are being used. See #38336 for an example. Alternatively, extend the phrasings that `electron/docs-parser` recognizes, and add the smoke tests. A (possibly non-exhaustive) list of ones which aren't being picked up. There's [an upstream issue](https://github.com/electron/docs-parser/issues/88) preventing certain values from being picked up. https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/webview-tag.md?plain=1#L1091-L1093 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/web-contents.md?plain=1#L796-L798 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/native-image.md?plain=1#L308-L309 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L577-L580 https://github.com/electron/electron/blob/2a16c73834358f85ef20c07e50dfb5178c30bb1e/docs/api/session.md?plain=1#L581-L582 https://github.com/electron/electron/blob/e08c583dea42ce70c926825a2f6d455bbddf2089/docs/api/desktop-capturer.md?plain=1#L91-L92
https://github.com/electron/electron/issues/38339
https://github.com/electron/electron/pull/39258
6df392162f1d29155e6d8d6f755de7e48c18e709
2b283724ce689a680b20c9b922384bec854415f6
2023-05-17T08:03:04Z
c++
2023-07-31T08:32:59Z
spec/ts-smoke/electron/main.ts
import { app, autoUpdater, BrowserWindow, contentTracing, dialog, desktopCapturer, globalShortcut, ipcMain, Menu, MenuItem, net, powerMonitor, powerSaveBlocker, protocol, Tray, screen, session, systemPreferences, webContents, TouchBar } from 'electron/main'; import { clipboard, crashReporter, nativeImage, shell } from 'electron/common'; import * as path from 'node:path'; // Quick start // https://github.com/electron/electron/blob/main/docs/tutorial/quick-start.md // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the javascript object is GCed. let mainWindow: Electron.BrowserWindow = null; // Quit when all windows are closed. app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); // Check single instance app const gotLock = app.requestSingleInstanceLock(); if (!gotLock) { app.quit(); process.exit(0); } // This method will be called when Electron has done everything // initialization and ready for creating browser windows. app.whenReady().then(() => { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600 }); // and load the index.html of the app. mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer' }); mainWindow.webContents.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer' }); mainWindow.webContents.loadURL('file://foo/bar', { userAgent: 'cool-agent', httpReferrer: 'greatReferrer', postData: [{ type: 'rawData', bytes: Buffer.from([123]) }] }); mainWindow.webContents.openDevTools(); mainWindow.webContents.toggleDevTools(); mainWindow.webContents.openDevTools({ mode: 'detach' }); mainWindow.webContents.closeDevTools(); mainWindow.webContents.addWorkSpace('/path/to/workspace'); mainWindow.webContents.removeWorkSpace('/path/to/workspace'); const opened = mainWindow.webContents.isDevToolsOpened(); console.log('isDevToolsOpened', opened); const focused = mainWindow.webContents.isDevToolsFocused(); console.log('isDevToolsFocused', focused); // Emitted when the window is closed. mainWindow.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); mainWindow.webContents.setVisualZoomLevelLimits(50, 200); mainWindow.webContents.print({ silent: true, printBackground: false }); mainWindow.webContents.print(); mainWindow.webContents.printToPDF({ margins: { top: 1 }, printBackground: true, pageRanges: '1-3', landscape: true }).then((data: Buffer) => console.log(data)); mainWindow.webContents.printToPDF({}).then(data => console.log(data)); mainWindow.webContents.executeJavaScript('return true;').then((v: boolean) => console.log(v)); mainWindow.webContents.executeJavaScript('return true;', true).then((v: boolean) => console.log(v)); mainWindow.webContents.executeJavaScript('return true;', true); mainWindow.webContents.executeJavaScript('return true;', true).then((result: boolean) => console.log(result)); mainWindow.webContents.insertText('blah, blah, blah'); mainWindow.webContents.startDrag({ file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png') }); mainWindow.webContents.findInPage('blah'); mainWindow.webContents.findInPage('blah', { forward: true, matchCase: false }); mainWindow.webContents.stopFindInPage('clearSelection'); mainWindow.webContents.stopFindInPage('keepSelection'); mainWindow.webContents.stopFindInPage('activateSelection'); mainWindow.loadURL('https://github.com'); mainWindow.webContents.on('did-finish-load', function () { mainWindow.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page saved successfully'); }); }); try { mainWindow.webContents.debugger.attach('1.1'); } catch (err) { console.log('Debugger attach failed : ', err); } mainWindow.webContents.debugger.on('detach', function (event, reason) { console.log('Debugger detached due to : ', reason); }); mainWindow.webContents.debugger.on('message', function (event, method, params: any) { if (method === 'Network.requestWillBeSent') { if (params.request.url === 'https://www.github.com') { mainWindow.webContents.debugger.detach(); } } }); mainWindow.webContents.debugger.sendCommand('Network.enable'); mainWindow.webContents.capturePage().then(image => { console.log(image.toDataURL()); }); mainWindow.webContents.capturePage({ x: 0, y: 0, width: 100, height: 200 }).then(image => { console.log(image.toPNG()); }); }); app.commandLine.appendSwitch('enable-web-bluetooth'); app.whenReady().then(() => { mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault(); const result = (() => { for (const device of deviceList) { if (device.deviceName === 'test') { return device; } } return null; })(); if (!result) { callback(''); } else { callback(result.deviceId); } }); }); // Locale app.getLocale(); // Desktop environment integration app.addRecentDocument('/Users/USERNAME/Desktop/work.type'); app.clearRecentDocuments(); const dockMenu = Menu.buildFromTemplate([ <Electron.MenuItemConstructorOptions> { label: 'New Window', click: () => { console.log('New Window'); } }, <Electron.MenuItemConstructorOptions> { label: 'New Window with Settings', submenu: [ <Electron.MenuItemConstructorOptions> { label: 'Basic' }, <Electron.MenuItemConstructorOptions> { label: 'Pro' } ] }, <Electron.MenuItemConstructorOptions> { label: 'New Command...' }, <Electron.MenuItemConstructorOptions> { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' } ] } ]); app.dock.setMenu(dockMenu); app.dock.setBadge('foo'); const dockid = app.dock.bounce('informational'); app.dock.cancelBounce(dockid); app.dock.setIcon('/path/to/icon.png'); app.setBadgeCount(app.getBadgeCount() + 1); app.setUserTasks([ <Electron.Task> { program: process.execPath, arguments: '--new-window', iconPath: process.execPath, iconIndex: 0, title: 'New Window', description: 'Create a new window', workingDirectory: path.dirname(process.execPath) } ]); app.setUserTasks([]); 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', iconPath: process.execPath, iconIndex: 0, description: 'Runs Tool A', workingDirectory: path.dirname(process.execPath) }, { type: 'task', title: 'Tool B', program: process.execPath, args: '--run-tool-b', iconPath: process.execPath, iconIndex: 0, description: 'Runs Tool B', workingDirectory: path.dirname(process.execPath) }] }, { 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' }] } ]); if (app.isUnityRunning()) { console.log('unity running'); } if (app.isAccessibilitySupportEnabled()) { console.log('a11y running'); } app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false }); console.log(app.getLoginItemSettings().wasOpenedAtLogin); app.setAboutPanelOptions({ applicationName: 'Test', version: '1.2.3' }); // Online/Offline Event Detection // https://github.com/electron/electron/blob/main/docs/tutorial/online-offline-events.md let onlineStatusWindow: Electron.BrowserWindow; app.whenReady().then(() => { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false, vibrancy: 'sidebar' }); onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); }); app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled)); ipcMain.on('online-status-changed', (event, status: any) => { console.log(status); }); app.whenReady().then(() => { window = new BrowserWindow({ width: 800, height: 600, titleBarStyle: 'hiddenInset' }); window.loadURL('https://github.com'); }); // Supported command line switches // https://github.com/electron/electron/blob/main/docs/api/command-line-switches.md app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); app.commandLine.appendSwitch('vmodule', 'console=0'); // systemPreferences // https://github.com/electron/electron/blob/main/docs/api/system-preferences.md const browserOptions = { width: 1000, height: 800, transparent: false, frame: true }; // Make the window transparent only if the platform supports it. if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.transparent = true; browserOptions.frame = false; } if (process.platform === 'win32') { systemPreferences.on('color-changed', () => { console.log('color changed'); }); systemPreferences.on('inverted-color-scheme-changed', (_, inverted) => console.log(inverted ? 'inverted' : 'not inverted')); console.log('Color for menu is', systemPreferences.getColor('menu')); } if (process.platform === 'darwin') { const value = systemPreferences.getUserDefault('Foo', 'string'); console.log(value); const value2 = systemPreferences.getUserDefault('Foo', 'boolean'); console.log(value2); } // Create the window. const win1 = new BrowserWindow(browserOptions); // Navigate. if (browserOptions.transparent) { win1.loadURL(`file://${__dirname}/index.html`); } else { // No transparency, so we load a fallback that uses basic styles. win1.loadURL(`file://${__dirname}/fallback.html`); } // app // https://github.com/electron/electron/blob/main/docs/api/app.md app.on('certificate-error', function (event, webContents, url, error, certificate, callback) { if (url === 'https://github.com') { // Verification logic. event.preventDefault(); callback(true); } else { callback(false); } }); app.on('select-client-certificate', function (event, webContents, url, list, callback) { event.preventDefault(); callback(list[0]); }); app.on('login', function (event, webContents, request, authInfo, callback) { event.preventDefault(); callback('username', 'secret'); }); const win2 = new BrowserWindow({ show: false }); win2.once('ready-to-show', () => { win2.show(); }); app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }); app.exit(0); // auto-updater // https://github.com/electron/electron/blob/main/docs/api/auto-updater.md autoUpdater.setFeedURL({ url: 'http://mycompany.com/myapp/latest?version=' + app.getVersion(), headers: { key: 'value' }, serverType: 'default' }); autoUpdater.checkForUpdates(); autoUpdater.quitAndInstall(); autoUpdater.on('error', (error) => { console.log('error', error); }); autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateURL) => { console.log('update-downloaded', releaseNotes, releaseName, releaseDate, updateURL); }); // BrowserWindow // https://github.com/electron/electron/blob/main/docs/api/browser-window.md let win3 = new BrowserWindow({ width: 800, height: 600, show: false }); win3.on('closed', () => { win3 = null; }); win3.loadURL('https://github.com'); win3.show(); const toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win3.setSheetOffset(toolbarRect.height); let window = new BrowserWindow(); window.setProgressBar(0.5); window.setRepresentedFilename('/etc/passwd'); window.setDocumentEdited(true); window.previewFile('/path/to/file'); window.previewFile('/path/to/file', 'Displayed Name'); window.setVibrancy('menu'); window.setVibrancy('titlebar'); window.setVibrancy('selection'); window.setVibrancy('popover'); window.setIcon('/path/to/icon'); // content-tracing // https://github.com/electron/electron/blob/main/docs/api/content-tracing.md const options = { categoryFilter: '*', traceOptions: 'record-until-full,enable-sampling' }; contentTracing.startRecording(options).then(() => { console.log('Tracing started'); setTimeout(function () { contentTracing.stopRecording('').then(path => { console.log(`Tracing data recorded to ${path}`); }); }, 5000); }); // dialog // https://github.com/electron/electron/blob/main/docs/api/dialog.md // variant without browserWindow dialog.showOpenDialogSync({ title: 'Testing showOpenDialog', defaultPath: '/var/log/syslog', filters: [{ name: '', extensions: [''] }], properties: ['openFile', 'openDirectory', 'multiSelections'] }); // variant with browserWindow dialog.showOpenDialog(win3, { title: 'Testing showOpenDialog', defaultPath: '/var/log/syslog', filters: [{ name: '', extensions: [''] }], properties: ['openFile', 'openDirectory', 'multiSelections'] }).then(ret => { console.log(ret); }); // variants without browserWindow dialog.showMessageBox({ message: 'test', type: 'warning' }); dialog.showMessageBoxSync({ message: 'test', type: 'error' }); // @ts-expect-error Invalid type value dialog.showMessageBox({ message: 'test', type: 'foo' }); // @ts-expect-error Invalid type value dialog.showMessageBoxSync({ message: 'test', type: 'foo' }); // variants with browserWindow dialog.showMessageBox(win3, { message: 'test', type: 'question' }); dialog.showMessageBoxSync(win3, { message: 'test', type: 'info' }); // @ts-expect-error Invalid type value dialog.showMessageBox(win3, { message: 'test', type: 'foo' }); // @ts-expect-error Invalid type value dialog.showMessageBoxSync(win3, { message: 'test', type: 'foo' }); // desktopCapturer // https://github.com/electron/electron/blob/main/docs/api/desktop-capturer.md ipcMain.handle('get-sources', (event, options) => desktopCapturer.getSources(options)); // global-shortcut // https://github.com/electron/electron/blob/main/docs/api/global-shortcut.md // Register a 'ctrl+x' shortcut listener. const ret = globalShortcut.register('ctrl+x', () => { console.log('ctrl+x is pressed'); }); if (!ret) { console.log('registration fails'); } // Check whether a shortcut is registered. console.log(globalShortcut.isRegistered('ctrl+x')); // Unregister a shortcut. globalShortcut.unregister('ctrl+x'); // Unregister all shortcuts. globalShortcut.unregisterAll(); // ipcMain // https://github.com/electron/electron/blob/main/docs/api/ipc-main.md ipcMain.on('asynchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.sender.send('asynchronous-reply', 'pong'); }); ipcMain.on('synchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.returnValue = 'pong'; }); ipcMain.on('synchronous-message', (event, arg: any) => { console.log(arg); // prints "ping" event.returnValue = 'pong'; }); const winWindows = new BrowserWindow({ width: 800, height: 600, show: false, thickFrame: false, type: 'toolbar' }); console.log(winWindows.id); // menu-item // https://github.com/electron/electron/blob/main/docs/api/menu-item.md const menuItem = new MenuItem({}); menuItem.label = 'Hello World!'; menuItem.click = (passedMenuItem: Electron.MenuItem, browserWindow: Electron.BrowserWindow) => { console.log('click', passedMenuItem, browserWindow); }; // menu // https://github.com/electron/electron/blob/main/docs/api/menu.md let menu = new Menu(); menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true })); menu.insert(0, menuItem); console.log(menu.items); const pos = screen.getCursorScreenPoint(); menu.popup({ x: pos.x, y: pos.y }); // main.js const template = <Electron.MenuItemConstructorOptions[]> [ { label: 'Electron', submenu: [ { label: 'About Electron', role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide Electron', accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: () => { app.quit(); } } ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+Command+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', role: 'cut' }, { label: 'Copy', accelerator: 'Command+C', role: 'copy' }, { label: 'Paste', accelerator: 'Command+V', role: 'paste' }, { label: 'Select All', accelerator: 'Command+A', role: 'selectall' } ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'Command+R', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.reloadIgnoringCache(); } } }, { label: 'Toggle DevTools', accelerator: 'Alt+Command+I', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.toggleDevTools(); } } }, { type: 'separator' }, { label: 'Actual Size', accelerator: 'CmdOrCtrl+0', click: (item, focusedWindow) => { if (focusedWindow) { focusedWindow.webContents.zoomLevel = 0; } } }, { label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', click: (item, focusedWindow) => { if (focusedWindow) { const { webContents } = focusedWindow; webContents.zoomLevel += 0.5; } } }, { label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', click: (item, focusedWindow) => { if (focusedWindow) { const { webContents } = focusedWindow; webContents.zoomLevel -= 0.5; } } } ] }, { label: 'Window', submenu: [ { label: 'Minimize', accelerator: 'Command+M', role: 'minimize' }, { label: 'Close', accelerator: 'Command+W', role: 'close' }, { type: 'separator' }, { label: 'Bring All to Front', role: 'front' } ] }, { label: 'Help', submenu: [] } ]; menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); // Must be called within app.whenReady().then(function(){ ... }); Menu.buildFromTemplate([ { label: '4', id: '4' }, { label: '5', id: '5', after: ['4'] }, { label: '1', id: '1', before: ['4'] }, { label: '2', id: '2' }, { label: '3', id: '3' } ]); Menu.buildFromTemplate([ { label: 'a' }, { label: '1' }, { label: 'b' }, { label: '2' }, { label: 'c' }, { label: '3' } ]); // All possible MenuItem roles Menu.buildFromTemplate([ { role: 'undo' }, { role: 'redo' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { role: 'reload' }, { role: 'forceReload' }, { role: 'toggleDevTools' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { role: 'togglefullscreen' }, { role: 'window' }, { role: 'minimize' }, { role: 'close' }, { role: 'help' }, { role: 'about' }, { role: 'services' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { role: 'quit' }, { role: 'startSpeaking' }, { role: 'stopSpeaking' }, { role: 'close' }, { role: 'minimize' }, { role: 'zoom' }, { role: 'front' }, { role: 'appMenu' }, { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }, { role: 'recentDocuments' }, { role: 'clearRecentDocuments' }, { role: 'toggleTabBar' }, { role: 'selectNextTab' }, { role: 'selectPreviousTab' }, { role: 'showAllTabs' }, { role: 'mergeAllWindows' }, { role: 'clearRecentDocuments' }, { role: 'moveTabToNewWindow' } ]); // net // https://github.com/electron/electron/blob/main/docs/api/net.md app.whenReady().then(() => { const request = net.request('https://github.com'); request.setHeader('Some-Custom-Header-Name', 'Some-Custom-Header-Value'); const header = request.getHeader('Some-Custom-Header-Name'); console.log('header', header); request.removeHeader('Some-Custom-Header-Name'); request.on('response', (response) => { console.log(`Status code: ${response.statusCode}`); console.log(`Status message: ${response.statusMessage}`); console.log(`Headers: ${JSON.stringify(response.headers)}`); console.log(`Http version: ${response.httpVersion}`); console.log(`Major Http version: ${response.httpVersionMajor}`); console.log(`Minor Http version: ${response.httpVersionMinor}`); response.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); response.on('end', () => { console.log('No more data in response.'); }); response.on('error', () => { console.log('"error" event emitted'); }); response.on('aborted', () => { console.log('"aborted" event emitted'); }); }); request.on('login', (authInfo, callback) => { callback('username', 'password'); }); request.on('finish', () => { console.log('"finish" event emitted'); }); request.on('abort', () => { console.log('"abort" event emitted'); }); request.on('error', () => { console.log('"error" event emitted'); }); request.write('Hello World!', 'utf-8'); request.end('Hello World!', 'utf-8'); request.abort(); }); // power-monitor // https://github.com/electron/electron/blob/main/docs/api/power-monitor.md app.whenReady().then(() => { powerMonitor.on('suspend', () => { console.log('The system is going to sleep'); }); powerMonitor.on('resume', () => { console.log('The system has resumed from sleep'); }); powerMonitor.on('on-ac', () => { console.log('The system changed to AC power'); }); powerMonitor.on('on-battery', () => { console.log('The system changed to battery power'); }); }); // power-save-blocker // https://github.com/electron/electron/blob/main/docs/api/power-save-blocker.md const id = powerSaveBlocker.start('prevent-display-sleep'); console.log(powerSaveBlocker.isStarted(id)); powerSaveBlocker.stop(id); // protocol // https://github.com/electron/electron/blob/main/docs/api/protocol.md app.whenReady().then(() => { protocol.registerSchemesAsPrivileged([{ scheme: 'https', privileges: { standard: true, allowServiceWorkers: true } }]); protocol.registerFileProtocol('atom', (request, callback) => { callback(`${__dirname}/${request.url}`); }); protocol.registerBufferProtocol('atom', (request, callback) => { callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') }); }); protocol.registerStringProtocol('atom', (request, callback) => { callback('Hello World!'); }); protocol.registerHttpProtocol('atom', (request, callback) => { callback({ url: request.url, method: request.method }); }); protocol.unregisterProtocol('atom'); const registered = protocol.isProtocolRegistered('atom'); console.log('isProtocolRegistered', registered); }); // tray // https://github.com/electron/electron/blob/main/docs/api/tray.md let appIcon: Electron.Tray = null; app.whenReady().then(() => { appIcon = new Tray('/path/to/my/icon'); const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }, { label: 'Item3', type: 'radio', checked: true }, { label: 'Item4', type: 'radio' } ]); appIcon.setTitle('title'); appIcon.setToolTip('This is my application.'); appIcon.setImage('/path/to/new/icon'); appIcon.setPressedImage('/path/to/new/icon'); appIcon.popUpContextMenu(contextMenu, { x: 100, y: 100 }); appIcon.setContextMenu(contextMenu); appIcon.setIgnoreDoubleClickEvents(true); appIcon.on('click', (event, bounds) => { console.log('click', event, bounds); }); appIcon.on('balloon-show', () => { console.log('balloon-show'); }); appIcon.displayBalloon({ title: 'Hello World!', content: 'This is the balloon content.', iconType: 'error', icon: 'path/to/icon', respectQuietTime: true, largeIcon: true, noSound: true }); }); // clipboard // https://github.com/electron/electron/blob/main/docs/api/clipboard.md clipboard.writeText('Example String'); clipboard.writeText('Example String', 'selection'); clipboard.writeBookmark('foo', 'http://example.com'); clipboard.writeBookmark('foo', 'http://example.com', 'selection'); clipboard.writeFindText('foo'); console.log(clipboard.readText('selection')); console.log(clipboard.readFindText()); console.log(clipboard.availableFormats()); console.log(clipboard.readBookmark().title); clipboard.clear(); clipboard.write({ html: '<html></html>', text: 'Hello World!', image: clipboard.readImage() }); // crash-reporter // https://github.com/electron/electron/blob/main/docs/api/crash-reporter.md crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', submitURL: 'https://your-domain.com/url-to-submit', uploadToServer: true, extra: { someKey: 'value' } }); console.log(crashReporter.getLastCrashReport()); console.log(crashReporter.getUploadedReports()); // nativeImage // https://github.com/electron/electron/blob/main/docs/api/native-image.md const appIcon2 = new Tray('/Users/somebody/images/icon.png'); appIcon2.destroy(); const window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); console.log(window2.id); const image = clipboard.readImage(); console.log(image.getSize()); const appIcon3 = new Tray(image); appIcon3.destroy(); const appIcon4 = new Tray('/Users/somebody/images/icon.png'); appIcon4.destroy(); const image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); console.log(image2.getSize()); // process // https://github.com/electron/electron/blob/main/docs/api/process.md console.log(process.versions.electron); console.log(process.versions.chrome); console.log(process.type); console.log(process.resourcesPath); console.log(process.mas); console.log(process.windowsStore); process.noAsar = true; process.crash(); process.hang(); process.setFdLimit(8192); // screen // https://github.com/electron/electron/blob/main/docs/api/screen.md app.whenReady().then(() => { const size = screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width: size.width, height: size.height }); }); app.whenReady().then(() => { const displays = screen.getAllDisplays(); let externalDisplay: any = null; for (const i in displays) { if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { externalDisplay = displays[i]; break; } } if (externalDisplay) { mainWindow = new BrowserWindow({ x: externalDisplay.bounds.x + 50, y: externalDisplay.bounds.y + 50 }); } screen.on('display-added', (event, display) => { console.log('display-added', display); }); screen.on('display-removed', (event, display) => { console.log('display-removed', display); }); screen.on('display-metrics-changed', (event, display, changes) => { console.log('display-metrics-changed', display, changes); }); }); // shell // https://github.com/electron/electron/blob/main/docs/api/shell.md shell.showItemInFolder('/home/user/Desktop/test.txt'); shell.trashItem('/home/user/Desktop/test.txt').then(() => {}); shell.openPath('/home/user/Desktop/test.txt').then(err => { if (err) console.log(err); }); shell.openExternal('https://github.com', { activate: false }).then(() => {}); shell.beep(); shell.writeShortcutLink('/home/user/Desktop/shortcut.lnk', 'update', shell.readShortcutLink('/home/user/Desktop/shortcut.lnk')); // cookies // https://github.com/electron/electron/blob/main/docs/api/cookies.md { // Query all cookies. session.defaultSession.cookies.get({}) .then(cookies => { console.log(cookies); }).catch((error: Error) => { console.log(error); }); // Query all cookies associated with a specific url. session.defaultSession.cookies.get({ url: 'http://www.github.com' }) .then(cookies => { console.log(cookies); }).catch((error: Error) => { console.log(error); }); // Set a cookie with the given cookie data; // may overwrite equivalent cookies if they exist. const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }; session.defaultSession.cookies.set(cookie) .then(() => { // success }, (error: Error) => { console.error(error); }); } // session // https://github.com/electron/electron/blob/main/docs/api/session.md session.defaultSession.on('will-download', (event, item, webContents) => { console.log('will-download', webContents.id); event.preventDefault(); require('got')(item.getURL()).then((data: any) => { require('node:fs').writeFileSync('/somewhere', data); }); }); // In the main process. session.defaultSession.on('will-download', (event, item, webContents) => { console.log('will-download', webContents.id); // Set the save path, making Electron not to prompt a save dialog. item.setSavePath('/tmp/save.pdf'); console.log(item.getSavePath()); console.log(item.getMimeType()); console.log(item.getFilename()); console.log(item.getTotalBytes()); item.on('updated', (_event, state) => { if (state === 'interrupted') { console.log('Download is interrupted but can be resumed'); } else if (state === 'progressing') { if (item.isPaused()) { console.log('Download is paused'); } else { console.log(`Received bytes: ${item.getReceivedBytes()}`); } } }); item.on('done', function (e, state) { if (state === 'completed') { console.log('Download successfully'); } else { console.log(`Download failed: ${state}`); } }); }); // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. session.defaultSession.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }); // To emulate a network outage. session.defaultSession.enableNetworkEmulation({ offline: true }); session.defaultSession.setCertificateVerifyProc((request, callback) => { const { hostname } = request; if (hostname === 'github.com') { callback(0); } else { callback(-2); } }); session.defaultSession.setPermissionRequestHandler(function (webContents, permission, callback) { if (webContents.getURL() === 'github.com') { if (permission === 'notifications') { callback(false); return; } } callback(true); }); // 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('*'); // Modify the user agent for all requests to the following urls. const filter = { urls: ['https://*.github.com/*', '*://electron.github.io'] }; session.defaultSession.webRequest.onBeforeSendHeaders(filter, function (details: any, callback: any) { details.requestHeaders['User-Agent'] = 'MyAgent'; callback({ cancel: false, requestHeaders: details.requestHeaders }); }); app.whenReady().then(function () { const protocol = session.defaultSession.protocol; protocol.registerFileProtocol('atom', function (request, callback) { const url = request.url.substr(7); callback(path.normalize(`${__dirname}/${url}`)); }); }); // webContents // https://github.com/electron/electron/blob/main/docs/api/web-contents.md console.log(webContents.getAllWebContents()); console.log(webContents.getFocusedWebContents()); const win4 = new BrowserWindow({ webPreferences: { offscreen: true } }); win4.webContents.on('paint', (event, dirty, _image) => { console.log(dirty, _image.getBitmap()); }); win4.webContents.on('devtools-open-url', (event, url) => { console.log(url); }); win4.loadURL('http://github.com'); // TouchBar // https://github.com/electron/electron/blob/main/docs/api/touch-bar.md const touchBar = new TouchBar({ items: [ new TouchBar.TouchBarButton({ label: '' }), new TouchBar.TouchBarLabel({ label: '' }) ] }); mainWindow.setTouchBar(touchBar);
closed
electron/electron
https://github.com/electron/electron
34,178
[Bug]: Chrome Extension V3 service_worker - Supported APIs do not function
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 13.6.9, 18.2.0, 20.0.0-nightly.20220505 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior For successful messages to be sent to and from the Service Worker in the extension. The test case provided uses Electron's supported Chrome APIs as defined here: https://www.electronjs.org/docs/latest/api/extensions#loading-extensions - A content page is supplied by this extension which simply calls "chrome.runtime.sendMessage" to send a message. - A service worker is supplied by this extension which calls - "chrome.runtime.onInstalled" to print a logging statement - "chrome.runtime.onMessage.addListener" to listen for messages, and to send a response. Expected to see the log message show up on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` `Hello sender, I received your message.` With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I was just installed.", source: chrome-extension:///<some_chrome_extension_id>/background.js` `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker and I just received a message.", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Actual Behavior Actual logs seen on any web page: `I'm a content script, and I'm going to try to send a message to anyone that is listening.` Actual logs seen in terminal: With the ELECTRON_ENABLE_LOGGING=1 env set, expected to see: `[xxx:INFO:CONSOLE(1)] "Hello, I'm a service worker", source: chrome-extension:///<some_chrome_extension_id>/background.js` ### Testcase Gist URL https://gist.github.com/schetle/8ea7451215b89c4cc28506f96e9f384a ### Additional Information By January of this upcoming year, Manifest V2 extensions will cease to function (please see: https://developer.chrome.com/docs/extensions/mv3/mv2-sunset/) Part of the migration process to get from a V2 -> V3 extension requires that background pages are replaced with service workers (please see: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#background-service-workers)
https://github.com/electron/electron/issues/34178
https://github.com/electron/electron/pull/39290
b2c62d6ad1fb0745544a20c85abef312c7196d14
c8f7a0e0522b0527082a23438da11bf6f148825c
2022-05-11T16:10:16Z
c++
2023-08-01T06:04:38Z
shell/browser/electron_browser_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/browser/electron_browser_client.h" #if BUILDFLAG(IS_WIN) #include <shlobj.h> #endif #include <memory> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/escape.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version.h" #include "components/embedder_support/user_agent_utils.h" #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck #include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/login_delegate.h" #include "content/public/browser/overlay_window.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/service_worker_version_base_info.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" #include "content/public/browser/url_loader_request_interceptor.h" #include "content/public/browser/weak_document_ptr.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/crypto_buildflags.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "mojo/public/cpp/bindings/binder_map.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/ssl/ssl_private_key.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_api_ipc_handler_impl.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/electron_web_contents_utility_handler_impl.h" #include "shell/browser/font_defaults.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/native_window.h" #include "shell/browser/net/network_context_service.h" #include "shell/browser/net/network_context_service_factory.h" #include "shell/browser/net/proxying_url_loader_factory.h" #include "shell/browser/net/proxying_websocket.h" #include "shell/browser/net/system_network_context_manager.h" #include "shell/browser/network_hints_handler_impl.h" #include "shell/browser/notifications/notification_presenter.h" #include "shell/browser/notifications/platform_notification_service.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/webauthn/electron_authenticator_request_delegate.h" #include "shell/browser/window_list.h" #include "shell/common/api/api.mojom.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "shell/common/thread_restrictions.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/badging/badging.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) #include "net/ssl/client_cert_store_win.h" #elif BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #elif defined(USE_OPENSSL) #include "net/ssl/client_cert_store.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck #endif #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #include "shell/browser/fake_location_provider.h" #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/webui_url_constants.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/web_ui_url_loader_factory.h" #include "extensions/browser/api/mime_handler_private/mime_handler_private.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_message_filter.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/extensions_guest_view.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/process_map.h" #include "extensions/browser/url_loader_factory_manager.h" #include "extensions/common/api/mime_handler.mojom.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/switches.h" #include "shell/browser/extensions/electron_extension_message_filter.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck #include "shell/browser/plugins/plugin_utils.h" #endif #if BUILDFLAG(IS_MAC) #include "content/browser/mac_helpers.h" #include "content/public/browser/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(IS_WIN) #include "chrome/browser/ui/views/overlay/video_overlay_window_views.h" #include "shell/browser/browser.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/win/shell.h" #include "ui/views/widget/widget.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "chrome/browser/pdf/chrome_pdf_stream_delegate.h" #include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h" // nogncheck #include "components/pdf/browser/pdf_navigation_throttle.h" #include "components/pdf/browser/pdf_url_loader_request_interceptor.h" #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "components/pdf/common/internal_plugin_helpers.h" #endif using content::BrowserThread; namespace electron { namespace { ElectronBrowserClient* g_browser_client = nullptr; base::LazyInstance<std::string>::DestructorAtExit g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER; base::NoDestructor<std::string> g_application_locale; void SetApplicationLocaleOnIOThread(const std::string& locale) { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_io_thread_application_locale.Get() = locale; } void BindNetworkHintsHandler( content::RenderFrameHost* frame_host, mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) { NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver)); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions // below. Extension, and isolated apps require different privileges to be // granted to their RenderProcessHosts. This classification allows us to make // sure URLs are served by hosts with the right set of privileges. enum class RenderProcessHostPrivilege { kNormal, kHosted, kIsolated, kExtension, }; // Copied from chrome/browser/extensions/extension_util.cc. bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( extensions::switches::kDisableExtensionsFileAccessCheck) || extensions::ExtensionPrefs::Get(context)->AllowFileAccess( extension_id); } RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, extensions::ExtensionRegistry* registry) { // Default to a normal renderer cause it is lower privileged. This should only // occur if the URL on a site instance is either malformed, or uninitialized. // If it is malformed, then there is no need for better privileges anyways. // If it is uninitialized, but eventually settles on being an a scheme other // than normal webrenderer, the navigation logic will correct us out of band // anyways. if (!url.is_valid()) return RenderProcessHostPrivilege::kNormal; if (!url.SchemeIs(extensions::kExtensionScheme)) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } RenderProcessHostPrivilege GetProcessPrivilege( content::RenderProcessHost* process_host, extensions::ProcessMap* process_map, extensions::ExtensionRegistry* registry) { std::set<std::string> extension_ids = process_map->GetExtensionsInProcess(process_host->GetID()); if (extension_ids.empty()) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } const extensions::Extension* GetEnabledExtensionFromEffectiveURL( content::BrowserContext* context, const GURL& effective_url) { if (!effective_url.SchemeIs(extensions::kExtensionScheme)) return nullptr; extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(context); if (!registry) return nullptr; return registry->enabled_extensions().GetByID(effective_url.host()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(IS_LINUX) int GetCrashSignalFD(const base::CommandLine& command_line) { int fd; return crash_reporter::GetHandlerSocket(&fd, nullptr) ? fd : -1; } #endif // BUILDFLAG(IS_LINUX) void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) { // |allowlist| combines pref/policy + cmdline switch in the browser process. // For renderer and utility (e.g. NetworkService) processes the switch is the // only available source, so below the combined (pref/policy + cmdline) // allowlist of secure origins is injected into |cmdline| for these other // processes. std::vector<std::string> allowlist = network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist(); if (!allowlist.empty()) { cmdline->AppendSwitchASCII( network::switches::kUnsafelyTreatInsecureOriginAsSecure, base::JoinString(allowlist, ",")); } } } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) { g_io_thread_application_locale.Get() = locale; } *g_application_locale = locale; } ElectronBrowserClient::ElectronBrowserClient() { DCHECK(!g_browser_client); g_browser_client = this; } ElectronBrowserClient::~ElectronBrowserClient() { DCHECK(g_browser_client); g_browser_client = nullptr; } content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the web contents // for the frame host passed into RegisterPendingProcess. const auto iter = pending_processes_.find(process_id); if (iter != std::end(pending_processes_)) return iter->second; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const { return nullptr; } bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const { return base::Contains(renderer_is_subframe_, process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { // When a render process is crashed, it might be reused. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) int process_id = host->GetID(); auto* browser_context = host->GetBrowserContext(); host->AddFilter( new extensions::ExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new ElectronExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new extensions::MessagingAPIMessageFilter(process_id, browser_context)); #endif // Remove in case the host is reused after a crash, otherwise noop. host->RemoveObserver(this); // ensure the ProcessPreferences is removed later host->AddObserver(this); } content::SpeechRecognitionManagerDelegate* ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new ElectronSpeechRecognitionManagerDelegate; } content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() { return nullptr; } void ElectronBrowserClient::OverrideWebkitPrefs( content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->webgl1_enabled = true; prefs->webgl2_enabled = true; prefs->allow_running_insecure_content = false; prefs->default_minimum_page_scale_factor = 1.f; prefs->default_maximum_page_scale_factor = 1.f; prefs->navigate_on_drag_drop = false; ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; SetFontDefaults(prefs); // Custom preferences of guest page. auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) { web_preferences->OverrideWebkitPrefs(prefs); } } void ElectronBrowserClient::RegisterPendingSiteInstance( content::RenderFrameHost* rfh, content::SiteInstance* pending_site_instance) { // Remember the original web contents for the pending renderer process. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* pending_process = pending_site_instance->GetProcess(); pending_processes_[pending_process->GetID()] = web_contents; if (rfh->GetParent()) renderer_is_subframe_.insert(pending_process->GetID()); else renderer_is_subframe_.erase(pending_process->GetID()); } void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable { ScopedAllowBlockingForElectron allow_blocking; base::FilePath child_path; base::FilePath program = base::MakeAbsoluteFilePath(command_line->GetProgram()); #if BUILDFLAG(IS_MAC) auto renderer_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_RENDERER); auto gpu_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_GPU); auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); if (program != renderer_child_path && program != gpu_child_path && program != plugin_child_path) { child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_NORMAL); CHECK_EQ(program, child_path) << "Aborted from launching unexpected helper executable"; } #else if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { CHECK(false) << "Unable to get child process binary name."; } SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe", child_path.AsUTF8Unsafe()); SCOPED_CRASH_KEY_STRING256("ChildProcess", "program", program.AsUTF8Unsafe()); CHECK_EQ(program, child_path); #endif } std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); #if BUILDFLAG(IS_LINUX) pid_t pid; if (crash_reporter::GetHandlerSocket(nullptr, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } // Zygote Process gets booted before any JS runs, accessing GetClientId // will end up touching DIR_USER_DATA path provider and this will // configure default value because app.name from browser_init has // not run yet. if (process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value); } #endif // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable // at that time. It doesn't need --user-data-dir to be correct anyway, since // the zygote itself doesn't access anything in that directory. if (process_type != ::switches::kZygoteProcess) { base::FilePath user_data_dir; if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir); } if (process_type == ::switches::kUtilityProcess || process_type == ::switches::kRendererProcess) { // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, switches::kEnableSandbox, switches::kSecureSchemes, switches::kBypassCSPSchemes, switches::kCORSSchemes, switches::kFetchSchemes, switches::kServiceWorkerSchemes, switches::kStreamingSchemes}; command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(), kCommonSwitchNames); if (process_type == ::switches::kUtilityProcess || content::RenderProcessHost::FromID(process_id)) { MaybeAppendSecureOriginsAllowlistSwitch(command_line); } } if (process_type == ::switches::kRendererProcess) { #if BUILDFLAG(IS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif if (delegate_) { auto app_path = static_cast<api::App*>(delegate_)->GetAppPath(); command_line->AppendSwitchPath(switches::kAppPath, app_path); } auto env = base::Environment::Create(); if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) { command_line->AppendSwitch("profile-electron-init"); } // Extension background pages don't have WebContentsPreferences, but they // support WebSQL by default. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) content::RenderProcessHost* process = content::RenderProcessHost::FromID(process_id); if (extensions::ProcessMap::Get(process->GetBrowserContext()) ->Contains(process_id)) command_line->AppendSwitch(switches::kEnableWebSQL); #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (web_contents) { auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) web_preferences->AppendCommandLineSwitches( command_line, IsRendererSubFrame(process_id)); } } } void ElectronBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) {} // attempt to get api key from env std::string ElectronBrowserClient::GetGeolocationApiKey() { auto env = base::Environment::Create(); std::string api_key; env->GetVar("GOOGLE_API_KEY", &api_key); return api_key; } content::GeneratedCodeCacheSettings ElectronBrowserClient::GetGeneratedCodeCacheSettings( content::BrowserContext* context) { // TODO(deepak1556): Use platform cache directory. base::FilePath cache_path = context->GetPath(); // If we pass 0 for size, disk_cache will pick a default size using the // heuristics based on available disk size. These are implemented in // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc. return content::GeneratedCodeCacheSettings(true, 0, cache_path); } void ElectronBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) { if (delegate_) { delegate_->AllowCertificateError(web_contents, cert_error, ssl_info, request_url, is_main_frame_request, strict_enforcement, std::move(callback)); } } base::OnceClosure ElectronBrowserClient::SelectClientCertificate( content::BrowserContext* browser_context, content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (client_certs.empty()) { delegate->ContinueWithCertificate(nullptr, nullptr); } else if (delegate_) { delegate_->SelectClientCertificate( browser_context, web_contents, cert_request_info, std::move(client_certs), std::move(delegate)); } return base::OnceClosure(); } bool ElectronBrowserClient::CanCreateWindow( content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(opener); WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents); if (prefs) { if (prefs->ShouldDisablePopups()) { // <webview> without allowpopups attribute should return // null from window.open calls return false; } else { *no_javascript_access = false; return true; } } if (delegate_) { return delegate_->CanCreateWindow( opener, opener_url, opener_top_level_frame_url, source_origin, container_type, target_url, referrer, frame_name, disposition, features, raw_features, body, user_gesture, opener_suppressed, no_javascript_access); } return false; } std::unique_ptr<content::VideoOverlayWindow> ElectronBrowserClient::CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) { auto overlay_window = content::VideoOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<VideoOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } void ElectronBrowserClient::GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); } void ElectronBrowserClient::SiteInstanceGotProcess( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Insert(extension->id(), site_instance->GetProcess()->GetID()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::IsSuitableHost( content::RenderProcessHost* process_host, const GURL& site_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = process_host->GetBrowserContext(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); // Otherwise, just make sure the process privilege matches the privilege // required by the site. RenderProcessHostPrivilege privilege_required = GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; #else return content::ContentBrowserClient::IsSuitableHost(process_host, site_url); #endif } bool ElectronBrowserClient::ShouldUseProcessPerSite( content::BrowserContext* browser_context, const GURL& effective_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const extensions::Extension* extension = GetEnabledExtensionFromEffectiveURL(browser_context, effective_url); return extension != nullptr; #else return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context, effective_url); #endif } void ElectronBrowserClient::GetMediaDeviceIDSalt( content::RenderFrameHost* rfh, const net::SiteForCookies& site_for_cookies, const blink::StorageKey& storage_key, base::OnceCallback<void(bool, const std::string&)> callback) { constexpr bool persistent_media_device_id_allowed = true; std::string persistent_media_device_id_salt = static_cast<ElectronBrowserContext*>(rfh->GetBrowserContext()) ->GetMediaDeviceIDSalt(); std::move(callback).Run(persistent_media_device_id_allowed, persistent_media_device_id_salt); } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } std::unique_ptr<net::ClientCertStore> ElectronBrowserClient::CreateClientCertStore( content::BrowserContext* browser_context) { #if BUILDFLAG(USE_NSS_CERTS) return std::make_unique<net::ClientCertStoreNSS>( net::ClientCertStoreNSS::PasswordDelegateFactory()); #elif BUILDFLAG(IS_WIN) return std::make_unique<net::ClientCertStoreWin>(); #elif BUILDFLAG(IS_MAC) return std::make_unique<net::ClientCertStoreMac>(); #elif defined(USE_OPENSSL) return std::unique_ptr<net::ClientCertStore>(); #endif } std::unique_ptr<device::LocationProvider> ElectronBrowserClient::OverrideSystemLocationProvider() { #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) return std::make_unique<FakeLocationProvider>(); #else return nullptr; #endif } void ElectronBrowserClient::ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) { DCHECK(browser_context); return NetworkContextServiceFactory::GetForContext(browser_context) ->ConfigureNetworkContextParams(network_context_params, cert_verifier_creation_params); } network::mojom::NetworkContext* ElectronBrowserClient::GetSystemNetworkContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_browser_process->system_network_context_manager()); return g_browser_process->system_network_context_manager()->GetContext(); } std::unique_ptr<content::BrowserMainParts> ElectronBrowserClient::CreateBrowserMainParts(bool /* is_integration_test */) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(); #if BUILDFLAG(IS_MAC) browser_main_parts_ = browser_main_parts.get(); #endif return browser_main_parts; } void ElectronBrowserClient::WebNotificationAllowed( content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { std::move(callback).Run(false, false); return; } auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { std::move(callback).Run(false, false); return; } permission_helper->RequestWebNotificationPermission( rfh, base::BindOnce(std::move(callback), web_contents->IsAudioMuted())); } void ElectronBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); pending_processes_.erase(process_id); renderer_is_subframe_.erase(process_id); host->RemoveObserver(this); } void ElectronBrowserClient::RenderProcessReady( content::RenderProcessHost* host) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessReady(host); } } void ElectronBrowserClient::RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessExited(host); } } void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) { platform_util::OpenExternal( escaped_url, platform_util::OpenExternalOptions(), base::DoNothing()); } } void HandleExternalProtocolInUI( const GURL& url, content::WeakDocumentPtr document_ptr, content::WebContents::OnceGetter web_contents_getter, bool has_user_gesture) { content::WebContents* web_contents = std::move(web_contents_getter).Run(); if (!web_contents) return; auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) return; content::RenderFrameHost* rfh = document_ptr.AsRenderFrameHostIfValid(); if (!rfh) { // If the render frame host is not valid it means it was a top level // navigation and the frame has already been disposed of. In this case we // take the current main frame and declare it responsible for the // transition. rfh = web_contents->GetPrimaryMainFrame(); } GURL escaped_url(base::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(rfh, std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_primary_main_frame, bool is_in_fenced_frame_tree, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&HandleExternalProtocolInUI, url, initiator_document ? initiator_document->GetWeakDocumentPtr() : content::WeakDocumentPtr(), std::move(web_contents_getter), has_user_gesture)); return true; } std::vector<std::unique_ptr<content::NavigationThrottle>> ElectronBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> pdf_throttle = pdf::PdfNavigationThrottle::MaybeCreateThrottleFor( handle, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_throttle) throttles.push_back(std::move(pdf_throttle)); #endif return throttles; } content::MediaObserver* ElectronBrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } std::unique_ptr<content::DevToolsManagerDelegate> ElectronBrowserClient::CreateDevToolsManagerDelegate() { return std::make_unique<DevToolsManagerDelegate>(); } NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() { if (!notification_presenter_) { notification_presenter_.reset(NotificationPresenter::Create()); } return notification_presenter_.get(); } content::PlatformNotificationService* ElectronBrowserClient::GetPlatformNotificationService() { if (!notification_service_) { notification_service_ = std::make_unique<PlatformNotificationService>(this); } return notification_service_.get(); } base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() { base::FilePath download_path; if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path)) return download_path; return base::FilePath(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserClient::GetSystemSharedURLLoaderFactory() { if (!g_browser_process) return nullptr; return g_browser_process->shared_url_loader_factory(); } void ElectronBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!g_browser_process) return; g_browser_process->system_network_context_manager()->OnNetworkServiceCreated( network_service); } std::vector<base::FilePath> ElectronBrowserClient::GetNetworkContextsParentDirectory() { base::FilePath session_data; base::PathService::Get(DIR_SESSION_DATA, &session_data); DCHECK(!session_data.empty()); return {session_data}; } std::string ElectronBrowserClient::GetProduct() { return "Chrome/" CHROME_VERSION_STRING; } std::string ElectronBrowserClient::GetUserAgent() { if (user_agent_override_.empty()) return GetApplicationUserAgent(); return user_agent_override_; } void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) { user_agent_override_ = user_agent; } blink::UserAgentMetadata ElectronBrowserClient::GetUserAgentMetadata() { return embedder_support::GetUserAgentMetadata(); } void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); content::BrowserContext* context = web_contents->GetBrowserContext(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionNavigationURLLoaderFactory( context, ukm_source_id, false /* we don't support extensions::WebViewGuest */)); #endif // Always allow navigating to file:// URLs. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context); protocol_registry->RegisterURLLoaderFactories(factories, true /* allow_file_access */); } void ElectronBrowserClient:: RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); // Workers are not allowed to request file:// URLs, there is no particular // reason for it, and we could consider supporting it in future. protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace { // The FileURLLoaderFactory provided to the extension background pages. // Checks with the ChildProcessSecurityPolicy to validate the file access. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory { public: static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create( int child_id) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; // The FileURLLoaderFactory will delete itself when there are no more // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method. new FileURLLoaderFactory(child_id, pending_remote.InitWithNewPipeAndPassReceiver()); return pending_remote; } // disable copy FileURLLoaderFactory(const FileURLLoaderFactory&) = delete; FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete; private: explicit FileURLLoaderFactory( int child_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver) : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)), child_id_(child_id) {} ~FileURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL( child_id_, request.url)) { mojo::Remote<network::mojom::URLLoaderClient>(std::move(client)) ->OnComplete( network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); return; } content::CreateFileURLLoaderBypassingSecurityChecks( request, std::move(loader), std::move(client), /*observer=*/nullptr, /* allow_directory_listing */ true); } int child_id_; }; } // namespace #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) { auto* render_process_host = content::RenderProcessHost::FromID(render_process_id); DCHECK(render_process_host); if (!render_process_host || !render_process_host->GetBrowserContext()) return; content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); // Allow accessing file:// subresources from non-file protocols if web // security is disabled. bool allow_file_access = false; if (web_contents) { const auto& web_preferences = web_contents->GetOrCreateWebPreferences(); if (!web_preferences.web_security_enabled) allow_file_access = true; } ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext()) ->RegisterURLLoaderFactories(factories, allow_file_access); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id, render_frame_id); if (factory) factories->emplace(extensions::kExtensionScheme, std::move(factory)); if (!web_contents) return; extensions::ElectronExtensionWebContentsObserver* web_observer = extensions::ElectronExtensionWebContentsObserver::FromWebContents( web_contents); // There is nothing to do if no ElectronExtensionWebContentsObserver is // attached to the |web_contents|. if (!web_observer) return; const extensions::Extension* extension = web_observer->GetExtensionFromFrame(frame_host, false); if (!extension) return; // Support for chrome:// scheme if appropriate. if (extension->is_extension() && extensions::Manifest::IsComponentLocation(extension->location())) { // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. factories->emplace(content::kChromeUIScheme, content::CreateWebUIURLLoaderFactory( frame_host, content::kChromeUIScheme, {content::kChromeUIResourcesHost})); } // Extensions with the necessary permissions get access to file:// URLs that // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with // ExtensionWebContentsObserver::RenderFrameCreated. extensions::Manifest::Type type = extension->GetType(); if (type == extensions::Manifest::TYPE_EXTENSION && AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) { factories->emplace(url::kFileScheme, FileURLLoaderFactory::Create(render_process_id)); } #endif } void ElectronBrowserClient:: RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { DCHECK(browser_context); DCHECK(factories); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); #if BUILDFLAG(ENABLE_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory( browser_context)); #endif // BUILDFLAG(ENABLE_EXTENSIONS) } bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) { if (is_embedded_origin_secure && scheme == content::kChromeUIScheme) return true; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) return scheme == extensions::kExtensionScheme; #else return false; #endif } bool ElectronBrowserClient::WillInterceptWebSocket( content::RenderFrameHost* frame) { if (!frame) return false; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); // NOTE: Some unit test environments do not initialize // BrowserContextKeyedAPI factories for e.g. WebRequest. if (!web_request.get()) return false; bool has_listener = web_request->HasListener(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get( browser_context); if (web_request_api) has_listener |= web_request_api->MayHaveProxies(); #endif return has_listener; } void ElectronBrowserClient::CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); if (web_request_api && web_request_api->MayHaveProxies()) { web_request_api->ProxyWebSocket(frame, std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client)); return; } } #endif ProxyingWebSocket::StartProxying( web_request.get(), std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client), true, frame->GetProcess()->GetID(), frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context, &next_id_); } bool ElectronBrowserClient::WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame_host, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); DCHECK(web_request_api); bool use_proxy_for_web_request = web_request_api->MaybeProxyURLLoaderFactory( browser_context, frame_host, render_process_id, type, navigation_id, ukm_source_id, factory_receiver, header_client, navigation_response_task_runner); if (bypass_redirect_checks) *bypass_redirect_checks = use_proxy_for_web_request; if (use_proxy_for_web_request) return true; } #endif auto proxied_receiver = std::move(*factory_receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote; *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); // Required by WebRequestInfoInitParams. // // Note that in Electron we allow webRequest to capture requests sent from // browser process, so creation of |navigation_ui_data| is different from // Chromium which only does for renderer-initialized navigations. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data; if (navigation_id.has_value()) { navigation_ui_data = std::make_unique<extensions::ExtensionNavigationUIData>(); } mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> header_client_receiver; if (header_client) header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); new ProxyingURLLoaderFactory( web_request.get(), protocol_registry->intercept_handlers(), render_process_id, frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE, &next_id_, std::move(navigation_ui_data), std::move(navigation_id), std::move(proxied_receiver), std::move(target_factory_remote), std::move(header_client_receiver), type); return true; } std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> ElectronBrowserClient::WillCreateURLLoaderRequestInterceptors( content::NavigationUIData* navigation_ui_data, int frame_tree_node_id, int64_t navigation_id, scoped_refptr<base::SequencedTaskRunner> navigation_response_task_runner) { std::vector<std::unique_ptr<content::URLLoaderRequestInterceptor>> interceptors; #if BUILDFLAG(ENABLE_PDF_VIEWER) { std::unique_ptr<content::URLLoaderRequestInterceptor> pdf_interceptor = pdf::PdfURLLoaderRequestInterceptor::MaybeCreateInterceptor( frame_tree_node_id, std::make_unique<ChromePdfStreamDelegate>()); if (pdf_interceptor) interceptors.push_back(std::move(pdf_interceptor)); } #endif return interceptors; } void ElectronBrowserClient::OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) { if (factory_params->top_frame_id) { // Bypass CORB and CORS when web security is disabled. auto* rfh = content::RenderFrameHost::FromFrameToken( factory_params->process_id, blink::LocalFrameToken(factory_params->top_frame_id.value())); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* prefs = WebContentsPreferences::From(web_contents); if (prefs && !prefs->IsWebSecurityEnabled()) { factory_params->is_corb_enabled = false; factory_params->disable_web_security = true; } } extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); } void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) auto* contents = content::WebContents::FromRenderFrameHost(&render_frame_host); if (contents) { auto* prefs = WebContentsPreferences::From(contents); if (render_frame_host.GetFrameTreeNodeId() == contents->GetPrimaryMainFrame()->GetFrameTreeNodeId() || (prefs && prefs->AllowsNodeIntegrationInSubFrames())) { associated_registry.AddInterface<mojom::ElectronApiIPC>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronApiIPC> receiver) { ElectronApiIPCHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); } } associated_registry.AddInterface<mojom::ElectronWebContentsUtility>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronWebContentsUtility> receiver) { ElectronWebContentsUtilityHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface<mojom::ElectronAutofillDriver>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> receiver) { AutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host); }, &render_frame_host)); #if BUILDFLAG(ENABLE_PRINTING) associated_registry.AddInterface<printing::mojom::PrintManagerHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) { PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_EXTENSIONS) associated_registry.AddInterface<extensions::mojom::LocalFrameHost>( base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) { extensions::ExtensionWebContentsObserver::BindLocalFrameHost( std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) associated_registry.AddInterface<pdf::mojom::PdfService>(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) { pdf::PDFWebContentsHelper::BindPdfService(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif } std::string ElectronBrowserClient::GetApplicationLocale() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) return g_io_thread_application_locale.Get(); return *g_application_locale; } bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() { // Enable site isolation. It is off by default in Chromium <= 69. return true; } void ElectronBrowserClient::BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) { #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) { SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver)); return; } #endif } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void BindMimeHandlerService( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService> receiver) { content::WebContents* contents = content::WebContents::FromRenderFrameHost(frame_host); auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(contents); if (!guest_view) return; extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver)); } void BindBeforeUnloadControl( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl> receiver) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return; auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents); if (!guest_view) return; guest_view->FuseBeforeUnloadControl(std::move(receiver)); } #endif void ElectronBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry->AddInterface<extensions::mojom::EventRouter>( base::BindRepeating(&extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface<extensions::mojom::GuestView>( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_process_host->GetID())); #endif } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) { map->Add<network_hints::mojom::NetworkHintsHandler>( base::BindRepeating(&BindNetworkHintsHandler)); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindFrameReceiver)); map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating( &content::KeyboardLockServiceImpl::CreateMojoService)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) map->Add<extensions::mime_handler::MimeHandlerService>( base::BindRepeating(&BindMimeHandlerService)); map->Add<extensions::mime_handler::BeforeUnloadControl>( base::BindRepeating(&BindBeforeUnloadControl)); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); if (!web_contents) return; const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL(); if (!site.SchemeIs(extensions::kExtensionScheme)) return; content::BrowserContext* browser_context = render_frame_host->GetProcess()->GetBrowserContext(); auto* extension = extensions::ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetByID(site.host()); if (!extension) return; extensions::ExtensionsBrowserClient::Get() ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host, extension); #endif } #if BUILDFLAG(IS_LINUX) void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->Share(kCrashDumpSignal, crash_signal_fd); } } #endif std::unique_ptr<content::LoginDelegate> ElectronBrowserClient::CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( auth_info, web_contents, is_main_frame, url, response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> ElectronBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( request.destination, frame_tree_node_id)); #endif return result; } base::flat_set<std::string> ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) { base::flat_set<std::string> mime_types; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context); for (const auto& pair : map) mime_types.insert(pair.first); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) mime_types.insert(pdf::kInternalPluginMimeType); #endif return mime_types; } content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() { if (!serial_delegate_) serial_delegate_ = std::make_unique<ElectronSerialDelegate>(); return serial_delegate_.get(); } content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() { if (!bluetooth_delegate_) bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>(); return bluetooth_delegate_.get(); } content::UsbDelegate* ElectronBrowserClient::GetUsbDelegate() { if (!usb_delegate_) usb_delegate_ = std::make_unique<ElectronUsbDelegate>(); return usb_delegate_.get(); } void BindBadgeServiceForServiceWorker( const content::ServiceWorkerVersionBaseInfo& info, mojo::PendingReceiver<blink::mojom::BadgeService> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* render_process_host = content::RenderProcessHost::FromID(info.process_id); if (!render_process_host) return; badging::BadgeManager::BindServiceWorkerReceiver( render_process_host, info.scope, std::move(receiver)); } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker( content::BrowserContext* browser_context, const content::ServiceWorkerVersionBaseInfo& service_worker_version_info, mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { return device::GeolocationManager::GetInstance(); } #endif content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } content::WebAuthenticationDelegate* ElectronBrowserClient::GetWebAuthenticationDelegate() { if (!web_authentication_delegate_) { web_authentication_delegate_ = std::make_unique<ElectronWebAuthenticationDelegate>(); } return web_authentication_delegate_.get(); } } // namespace electron